/*      */ package com.zimbra.cs.zclient;
/*      */ 
/*      */ import com.zimbra.client.ZAce;
/*      */ import com.zimbra.client.ZAce.GranteeType;
/*      */ import com.zimbra.client.ZAppointmentHit;
/*      */ import com.zimbra.client.ZAutoCompleteMatch;
/*      */ import com.zimbra.client.ZContact;
/*      */ import com.zimbra.client.ZContact.Flag;
/*      */ import com.zimbra.client.ZContactHit;
/*      */ import com.zimbra.client.ZConversation;
/*      */ import com.zimbra.client.ZConversation.Flag;
/*      */ import com.zimbra.client.ZConversation.ZMessageSummary;
/*      */ import com.zimbra.client.ZConversationHit;
/*      */ import com.zimbra.client.ZDocument;
/*      */ import com.zimbra.client.ZDocumentHit;
/*      */ import com.zimbra.client.ZEmailAddress;
/*      */ import com.zimbra.client.ZFilterRule;
/*      */ import com.zimbra.client.ZFilterRules;
/*      */ import com.zimbra.client.ZFolder;
/*      */ import com.zimbra.client.ZFolder.Color;
/*      */ import com.zimbra.client.ZFolder.View;
/*      */ import com.zimbra.client.ZGetMessageParams;
/*      */ import com.zimbra.client.ZGrant;
/*      */ import com.zimbra.client.ZGrant.GranteeType;
/*      */ import com.zimbra.client.ZIdentity;
/*      */ import com.zimbra.client.ZItem.Flag;
/*      */ import com.zimbra.client.ZJSONObject;
/*      */ import com.zimbra.client.ZMailbox;
/*      */ import com.zimbra.client.ZMailbox.Fetch;
/*      */ import com.zimbra.client.ZMailbox.GalEntryType;
/*      */ import com.zimbra.client.ZMailbox.Options;
/*      */ import com.zimbra.client.ZMailbox.OwnerBy;
/*      */ import com.zimbra.client.ZMailbox.SharedItemBy;
/*      */ import com.zimbra.client.ZMailbox.ZApptSummaryResult;
/*      */ import com.zimbra.client.ZMailbox.ZSearchGalResult;
/*      */ import com.zimbra.client.ZMessage;
/*      */ import com.zimbra.client.ZMessage.ZMimePart;
/*      */ import com.zimbra.client.ZMessageHit;
/*      */ import com.zimbra.client.ZMountpoint;
/*      */ import com.zimbra.client.ZSearchFolder;
/*      */ import com.zimbra.client.ZSearchHit;
/*      */ import com.zimbra.client.ZSearchPagerResult;
/*      */ import com.zimbra.client.ZSearchParams;
/*      */ import com.zimbra.client.ZSearchResult;
/*      */ import com.zimbra.client.ZSignature;
/*      */ import com.zimbra.client.ZTag;
/*      */ import com.zimbra.client.ZTag.Color;
/*      */ import com.zimbra.client.event.ZCreateEvent;
/*      */ import com.zimbra.client.event.ZDeleteEvent;
/*      */ import com.zimbra.client.event.ZEventHandler;
/*      */ import com.zimbra.client.event.ZModifyEvent;
/*      */ import com.zimbra.client.event.ZRefreshEvent;
/*      */ import com.zimbra.common.account.Key.AccountBy;
/*      */ import com.zimbra.common.auth.ZAuthToken;
/*      */ import com.zimbra.common.localconfig.KnownKey;
/*      */ import com.zimbra.common.localconfig.LC;
/*      */ import com.zimbra.common.mailbox.ContactConstants.Attr;
/*      */ import com.zimbra.common.service.ServiceException;
/*      */ import com.zimbra.common.soap.Element;
/*      */ import com.zimbra.common.soap.SoapTransport;
/*      */ import com.zimbra.common.soap.SoapTransport.DebugListener;
/*      */ import com.zimbra.common.util.ByteUtil;
/*      */ import com.zimbra.common.util.CliUtil;
/*      */ import com.zimbra.common.util.DateUtil;
/*      */ import com.zimbra.common.util.EmailUtil;
/*      */ import com.zimbra.common.util.HttpUtil;
/*      */ import com.zimbra.common.util.StringUtil;
/*      */ import com.zimbra.common.zclient.ZClientException;
/*      */ import com.zimbra.common.zmime.ZMimeMessage;
/*      */ import com.zimbra.cs.account.accesscontrol.Right;
/*      */ import com.zimbra.cs.account.accesscontrol.RightManager;
/*      */ import com.zimbra.cs.account.soap.SoapAccountInfo;
/*      */ import com.zimbra.cs.account.soap.SoapProvisioning;
/*      */ import com.zimbra.cs.account.soap.SoapProvisioning.DelegateAuthResponse;
/*      */ import com.zimbra.cs.util.BuildInfo;
/*      */ import com.zimbra.cs.util.SoapCLI;
/*      */ import com.zimbra.soap.type.SearchSortBy;
/*      */ import java.io.BufferedInputStream;
/*      */ import java.io.BufferedReader;
/*      */ import java.io.ByteArrayInputStream;
/*      */ import java.io.File;
/*      */ import java.io.FileInputStream;
/*      */ import java.io.FileNotFoundException;
/*      */ import java.io.FileOutputStream;
/*      */ import java.io.IOException;
/*      */ import java.io.InputStream;
/*      */ import java.io.InputStreamReader;
/*      */ import java.io.OutputStream;
/*      */ import java.io.OutputStreamWriter;
/*      */ import java.io.PrintStream;
/*      */ import java.io.PrintWriter;
/*      */ import java.io.UnsupportedEncodingException;
/*      */ import java.net.URI;
/*      */ import java.net.URISyntaxException;
/*      */ import java.util.ArrayList;
/*      */ import java.util.Calendar;
/*      */ import java.util.Collection;
/*      */ import java.util.Collections;
/*      */ import java.util.Comparator;
/*      */ import java.util.Date;
/*      */ import java.util.HashMap;
/*      */ import java.util.List;
/*      */ import java.util.Map;
/*      */ import java.util.Map.Entry;
/*      */ import java.util.Properties;
/*      */ import java.util.TimeZone;
/*      */ import java.util.regex.Matcher;
/*      */ import java.util.regex.Pattern;
/*      */ import java.util.zip.GZIPInputStream;
/*      */ import javax.mail.MessagingException;
/*      */ import javax.mail.Session;
/*      */ import javax.mail.internet.MimeMessage;
/*      */ import javax.mail.util.SharedByteArrayInputStream;
/*      */ import org.apache.commons.cli.CommandLine;
/*      */ import org.apache.commons.cli.CommandLineParser;
/*      */ import org.apache.commons.cli.GnuParser;
/*      */ import org.apache.commons.cli.Option;
/*      */ import org.apache.commons.cli.Options;
/*      */ import org.apache.commons.cli.ParseException;
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ public class ZMailboxUtil
/*      */   implements SoapTransport.DebugListener
/*      */ {
/*  139 */   private boolean mInteractive = false;
/*  140 */   private boolean mGlobalVerbose = false;
/*  141 */   private boolean mDebug = false;
/*  142 */   private String mAdminAccountName = null;
/*  143 */   private String mAuthAccountName = null;
/*  144 */   private String mTargetAccountName = null;
/*  145 */   private String mPassword = null;
/*  146 */   private ZAuthToken mAdminAuthToken = null;
/*      */   
/*  148 */   private static final String DEFAULT_ADMIN_URL = "https://" + LC.zimbra_zmprov_default_soap_server.value() + ":" + LC.zimbra_admin_service_port.intValue() + "/";
/*  149 */   private static final String DEFAULT_URL = "http://" + LC.zimbra_zmprov_default_soap_server.value() + (LC.zimbra_mail_service_port.intValue() == 80 ? "" : new StringBuilder().append(":").append(LC.zimbra_mail_service_port.intValue()).toString()) + "/";
/*      */   
/*      */ 
/*  152 */   private String mUrl = DEFAULT_URL;
/*      */   
/*      */   private Map<String, Command> mCommandIndex;
/*      */   private ZMailbox mMbox;
/*  156 */   private String mPrompt = "mbox> ";
/*      */   ZSearchParams mSearchParams;
/*      */   int mSearchPage;
/*      */   ZSearchParams mConvSearchParams;
/*      */   ZSearchResult mConvSearchResult;
/*      */   SoapProvisioning mProv;
/*  162 */   private int mTimeout = LC.httpclient_internal_connmgr_so_timeout.intValue();
/*      */   
/*  164 */   private final Map<Integer, String> mIndexToId = new HashMap();
/*      */   
/*      */ 
/*      */   private Command mCommand;
/*      */   
/*      */ 
/*      */   private CommandLine mCommandLine;
/*      */   
/*      */ 
/*  173 */   private final CommandLineParser mParser = new GnuParser();
/*      */   
/*  175 */   public void setDebug(boolean debug) { this.mDebug = debug; }
/*      */   
/*  177 */   public void setVerbose(boolean verbose) { this.mGlobalVerbose = verbose; }
/*      */   
/*  179 */   public void setInteractive(boolean interactive) { this.mInteractive = interactive; }
/*      */   
/*  181 */   public void setAdminAccountName(String account) { this.mAdminAccountName = account; }
/*      */   
/*  183 */   public void setAuthAccountName(String account) { this.mAuthAccountName = account; }
/*      */   
/*  185 */   public void setTargetAccountName(String account) { this.mTargetAccountName = account; }
/*      */   
/*  187 */   public void setPassword(String password) { this.mPassword = password; }
/*      */   
/*  189 */   public void setAdminAuthToken(ZAuthToken authToken) { this.mAdminAuthToken = authToken; }
/*      */   
/*      */   public void setUrl(String url, boolean admin) throws ServiceException {
/*  192 */     this.mUrl = ZMailbox.resolveUrl(url, admin);
/*      */   }
/*      */   
/*      */   public void setTimeout(String timeout) throws ServiceException {
/*      */     int num;
/*      */     try {
/*  198 */       num = Integer.parseInt(timeout);
/*      */     } catch (NumberFormatException e) {
/*  200 */       throw ServiceException.INVALID_REQUEST("Invalid timeout value " + timeout, e);
/*      */     }
/*  202 */     if (num < 0) {
/*  203 */       throw ServiceException.INVALID_REQUEST("Timeout can't be negative", null);
/*      */     }
/*  205 */     if (num > 2147483) {
/*  206 */       throw ServiceException.INVALID_REQUEST("Timeout can't exceed 2147483 seconds", null);
/*      */     }
/*  208 */     this.mTimeout = (num * 1000);
/*      */   }
/*      */   
/*      */   private void usage() {
/*  212 */     if (this.mCommand != null) {
/*  213 */       stdout.printf("usage:%n%n%s%n", new Object[] { this.mCommand.getFullUsage() });
/*      */     }
/*      */     
/*  216 */     if (this.mInteractive) {
/*  217 */       return;
/*      */     }
/*  219 */     stdout.println("");
/*  220 */     stdout.println("zmmailbox [args] [cmd] [cmd-args ...]");
/*  221 */     stdout.println("");
/*  222 */     stdout.println("  -h/--help                                display usage");
/*  223 */     stdout.println("  -f/--file                                use file as input stream");
/*  224 */     stdout.println("  -u/--url      http[s]://{host}[:{port}]  server hostname and optional port. must use admin port with -z/-a");
/*  225 */     stdout.println("  -a/--admin    {name}                     admin account name to auth as");
/*  226 */     stdout.println("  -z/--zadmin                              use zimbra admin name/password from localconfig for admin/password");
/*  227 */     stdout.println("  -y/--authtoken {authtoken}               " + SoapCLI.OPT_AUTHTOKEN.getDescription());
/*  228 */     stdout.println("  -Y/--authtokenfile {authtoken file}      " + SoapCLI.OPT_AUTHTOKENFILE.getDescription());
/*  229 */     stdout.println("  -m/--mailbox  {name}                     mailbox to open");
/*  230 */     stdout.println("     --auth     {name}                     account name to auth as; defaults to -m unless -A is used");
/*  231 */     stdout.println("  -A/--admin-priv                          execute requests with admin privileges");
/*  232 */     stdout.println("                                           requires -z or -a, and -m");
/*  233 */     stdout.println("  -p/--password {pass}                     auth password");
/*  234 */     stdout.println("  -P/--passfile {file}                     read password from file");
/*  235 */     stdout.println("  -t/--timeout                             timeout (in seconds)");
/*  236 */     stdout.println("  -v/--verbose                             verbose mode (dumps full exception stack trace)");
/*  237 */     stdout.println("  -d/--debug                               debug mode (dumps SOAP messages)");
/*      */     
/*  239 */     stdout.println("");
/*  240 */     doHelp(null);
/*  241 */     System.exit(1);
/*      */   }
/*      */   
/*      */   public static enum Category {
/*  245 */     ADMIN("help on admin-related commands"), 
/*  246 */     ACCOUNT("help on account-related commands"), 
/*  247 */     APPOINTMENT("help on appoint-related commands", " absolute date-specs:\n\n  mm/dd/yyyy (i.e., 12/25/1998)\n  yyyy/dd/mm (i.e., 1989/12/25)\n  \\d+       (num milliseconds, i.e., 1132276598000)\n\n  relative date-specs:\n\n  [mp+-]?([0-9]+)([mhdwy][a-z]*)?g\n \n   +/{not-specified}   current time plus an offset\n   -                   current time minus an offset\n  \n   (0-9)+    value\n\n   ([mhdwy][a-z]*)  units, everything after the first character is ignored (except for \"mi\" case):\n   m(onths)\n   mi(nutes)\n   d(ays)\n   w(eeks)\n   h(ours)\n   y(ears)\n   \n  examples:\n     1day     1 day from now\n    +1day     1 day from now \n    p1day     1 day from now\n    +60mi     60 minutes from now\n    +1week    1 week from now\n    +6mon     6 months from now \n    1year     1 year from now\n\n"), 
/*      */     
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*  280 */     COMMANDS("help on all commands"), 
/*  281 */     CONTACT("help on contact-related commands"), 
/*  282 */     CONVERSATION("help on conversation-related commands"), 
/*  283 */     FILTER("help on filter-realted commnds", "  {conditions}:\n    address \"comma-separated-header-names\" all|localpart|domain is|not_is|contains|not_contains|matches|not_matches [case_sensitive] \"value\"\n    addressbook in|not_in \"header-name\"\n    attachment exists|not_exists\n    body contains|not_contains [case_sensitive] \"text\"\n    bulk [not]\n    conversation where|not_where started|participated\n    current_day_of_week is|not_is \"comma-separated-days(0=Sun,6=Sat)\"\n    current_time before|not_before|after|not_after \"HHmm\"\n    date before|not_before|after|not_after \"YYYYMMDD\"\n    facebook [not]\n    flagged [not] \"flag\"\n    header \"comma-separated-names\" is|not_is|contains|not_contains|matches|not_matches [case_sensitive] \"value\"\n    header \"comma-separated-names\" exists|not_exists\n    importance is|not_is high|normal|low\n    invite exists|not_exists\n    linkedin [not]\n    list [not]\n    me in|not_in \"header-name\"\n    mime_header \"name\" is|not_is|contains|not_contains|matches|not_matches [case_sensitive] \"value\"\n    ranking in|not_in \"header-name\"\n    size under|not_under|over|not_over \"1|1K|1M\"\n    socialcast [not]\n    twitter [not]\n\n  {actions}:\n    keep\n    discard\n    fileinto \"/path\"\n    tag \"tag\"\n    flag \"flag\"\n    mark read|flagged|priority\n    redirect \"address\"\n    reply \"body-template\"\n    notify \"address\" \"subject-template\" \"body-template\" [\"max-body-size(bytes)\"]\n    stop\n"), 
/*      */     
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*  320 */     FOLDER("help on folder-related commands"), 
/*  321 */     ITEM("help on item-related commands"), 
/*  322 */     MESSAGE("help on message-related commands"), 
/*  323 */     MISC("help on misc commands"), 
/*  324 */     RIGHT("help on right commands", "To grant/revoke rights on entries an account can inherit grants from(group, domain, global), use \"zmprov grr/rvr\" commands."), 
/*      */     
/*  326 */     SEARCH("help on search-related commands"), 
/*  327 */     TAG("help on tag-related commands");
/*      */     
/*      */     String mDesc;
/*      */     String mCategoryHelp;
/*      */     
/*  332 */     public String getDescription() { return this.mDesc; }
/*  333 */     public String getCategoryHelp() { return this.mCategoryHelp; }
/*      */     
/*      */     private Category(String desc) {
/*  336 */       this.mDesc = desc;
/*      */     }
/*      */     
/*      */     private Category(String desc, String help) {
/*  340 */       this.mDesc = desc;
/*  341 */       this.mCategoryHelp = help;
/*      */     }
/*      */   }
/*      */   
/*      */   public static Option getOption(String shortName, String longName, boolean hasArgs, String help) {
/*  346 */     return new Option(shortName, longName, hasArgs, help);
/*      */   }
/*      */   
/*  349 */   static Option O_AUTH = new Option(null, "auth", true, "account to auth as");
/*  350 */   static Option O_AS_ADMIN = new Option("A", "admin-priv", false, "execute requests with admin privileges");
/*  351 */   static Option O_AFTER = new Option("a", "after", true, "add after filter-name");
/*  352 */   static Option O_BEFORE = new Option("b", "before", true, "add before filter-name");
/*  353 */   static Option O_COLOR = new Option("c", "color", true, "color");
/*  354 */   static Option O_CONTENT_TYPE = new Option("c", "contentType", true, "content-type");
/*  355 */   static Option O_CURRENT = new Option("c", "current", false, "current page of search results");
/*  356 */   static Option O_DATE = new Option("d", "date", true, "received date (msecs since epoch)");
/*  357 */   static Option O_FIRST = new Option("f", "first", false, "add as first filter rule");
/*  358 */   static Option O_FLAGS = new Option("F", "flags", true, "flags");
/*  359 */   static Option O_FOLDER = new Option("f", "folder", true, "folder-path-or-id");
/*  360 */   static Option O_IGNORE = new Option("i", "ignore", false, "ignore unknown contact attrs");
/*  361 */   static Option O_IGNORE_ERROR = new Option("i", "ignore", false, "ignore and continue on error during ics import");
/*  362 */   static Option O_LAST = new Option("l", "last", false, "add as last filter rule");
/*  363 */   static Option O_LIMIT = new Option("l", "limit", true, "max number of results to return (1-1000, default=25)");
/*  364 */   static Option O_NEXT = new Option("n", "next", false, "next page of search results");
/*  365 */   static Option O_OUTPUT_FILE = new Option("o", "output", true, "output filename");
/*  366 */   static Option O_PRESERVE_ALARMS = new Option(null, "preserveAlarms", false, "preserve existing calendar alarms during ics import (default is to use alarms in ics file)");
/*      */   
/*  368 */   static Option O_START_TIME = new Option(null, "startTime", true, "start time for ics export");
/*  369 */   static Option O_END_TIME = new Option(null, "endTime", true, "end time for ics export");
/*  370 */   static Option O_PREVIOUS = new Option("p", "previous", false, "previous page of search results");
/*  371 */   static Option O_SORT = new Option("s", "sort", true, "sort order TODO");
/*  372 */   static Option O_REPLACE = new Option("r", "replace", false, "replace contact (default is to merge)");
/*  373 */   static Option O_TAGS = new Option("T", "tags", true, "list of tag ids/names");
/*  374 */   static Option O_TYPES = new Option("t", "types", true, "list of types to search for (message,conversation,contact,appointment,document,task,wiki)");
/*  375 */   static Option O_URL = new Option("u", "url", true, "url to connect to");
/*  376 */   static Option O_VERBOSE = new Option("v", "verbose", false, "verbose output");
/*  377 */   static Option O_VIEW = new Option("V", "view", true, "default type for folder (appointment,contact,conversation,document,message,task,wiki)");
/*  378 */   static Option O_NO_VALIDATION = new Option(null, "noValidation", false, "don't validate file content");
/*  379 */   static Option O_DUMPSTER = new Option(null, "dumpster", false, "search in dumpster");
/*      */   private static final long KBYTES = 1024L;
/*      */   
/*  382 */   static enum Command { ADD_INCOMING_FILTER_RULE("addFilterRule", "afrl", "{name}  [*active|inactive] [any|*all] {conditions}+ {actions}+", "add incoming filter rule", ZMailboxUtil.Category.FILTER, 2, Integer.MAX_VALUE, new Option[] { ZMailboxUtil.O_AFTER, ZMailboxUtil.O_BEFORE, ZMailboxUtil.O_FIRST, ZMailboxUtil.O_LAST }), 
/*  383 */     ADD_OUTGOING_FILTER_RULE("addOutgoingFilterRule", "aofrl", "{name}  [*active|inactive] [any|*all] {conditions}+ {actions}+", "add outgoing filter rule", ZMailboxUtil.Category.FILTER, 2, Integer.MAX_VALUE, new Option[] { ZMailboxUtil.O_AFTER, ZMailboxUtil.O_BEFORE, ZMailboxUtil.O_FIRST, ZMailboxUtil.O_LAST }), 
/*  384 */     ADD_MESSAGE("addMessage", "am", "{dest-folder-path} {filename-or-dir} [{filename-or-dir} ...]", "add a message to a folder", ZMailboxUtil.Category.MESSAGE, 2, Integer.MAX_VALUE, new Option[] { ZMailboxUtil.O_TAGS, ZMailboxUtil.O_DATE, ZMailboxUtil.O_FLAGS, ZMailboxUtil.O_NO_VALIDATION }), 
/*  385 */     ADMIN_AUTHENTICATE("adminAuthenticate", "aa", "{admin-name} {admin-password}", "authenticate as an admin. can only be used by an admin", ZMailboxUtil.Category.ADMIN, 2, 2, new Option[] { ZMailboxUtil.O_URL }), 
/*  386 */     AUTHENTICATE("authenticate", "a", "{auth-account-name} {password} [target-account-name]", "authenticate as account and open target mailbox; target defaults to auth account if unspecified", ZMailboxUtil.Category.MISC, 2, 3, new Option[] { ZMailboxUtil.O_URL }), 
/*  387 */     AUTO_COMPLETE("autoComplete", "ac", "{query}", "contact auto autocomplete", ZMailboxUtil.Category.CONTACT, 1, 1, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  388 */     AUTO_COMPLETE_GAL("autoCompleteGal", "acg", "{query}", "gal auto autocomplete", ZMailboxUtil.Category.CONTACT, 1, 1, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  389 */     CHECK_RIGHT("checkRight", "ckr", "{name} {right}", "check if the user has the specified right on target.", ZMailboxUtil.Category.RIGHT, 2, 2, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  390 */     CREATE_CONTACT("createContact", "cct", "[attr1 value1 [attr2 value2...]]", "create contact", ZMailboxUtil.Category.CONTACT, 2, Integer.MAX_VALUE, new Option[] { ZMailboxUtil.O_FOLDER, ZMailboxUtil.O_IGNORE, ZMailboxUtil.O_TAGS }), 
/*  391 */     CREATE_FOLDER("createFolder", "cf", "{folder-path}", "create folder", ZMailboxUtil.Category.FOLDER, 1, 1, new Option[] { ZMailboxUtil.O_VIEW, ZMailboxUtil.O_COLOR, ZMailboxUtil.O_FLAGS, ZMailboxUtil.O_URL }), 
/*  392 */     CREATE_IDENTITY("createIdentity", "cid", "{identity-name} [attr1 value1 [attr2 value2...]]", "create identity", ZMailboxUtil.Category.ACCOUNT, 1, Integer.MAX_VALUE, new Option[0]), 
/*  393 */     CREATE_MOUNTPOINT("createMountpoint", "cm", "{folder-path} {owner-id-or-name} {remote-item-id-or-path} [{reminder-enabled (0*|1)}]", "create mountpoint", ZMailboxUtil.Category.FOLDER, 3, 4, new Option[] { ZMailboxUtil.O_VIEW, ZMailboxUtil.O_COLOR, ZMailboxUtil.O_FLAGS }), 
/*  394 */     CREATE_SEARCH_FOLDER("createSearchFolder", "csf", "{folder-path} {query}", "create search folder", ZMailboxUtil.Category.FOLDER, 2, 2, new Option[] { ZMailboxUtil.O_SORT, ZMailboxUtil.O_TYPES, ZMailboxUtil.O_COLOR }), 
/*  395 */     CREATE_SIGNATURE("createSignature", "csig", "{signature-name} [signature-value}", "create signature", ZMailboxUtil.Category.ACCOUNT, 2, 2, new Option[0]), 
/*  396 */     CREATE_TAG("createTag", "ct", "{tag-name}", "create tag", ZMailboxUtil.Category.TAG, 1, 1, new Option[] { ZMailboxUtil.O_COLOR }), 
/*  397 */     DELETE_CONTACT("deleteContact", "dct", "{contact-ids}", "hard delete contact(s)", ZMailboxUtil.Category.CONTACT, 1, 1, new Option[0]), 
/*  398 */     DELETE_CONVERSATION("deleteConversation", "dc", "{conv-ids}", "hard delete conversastion(s)", ZMailboxUtil.Category.CONVERSATION, 1, 1, new Option[0]), 
/*  399 */     DELETE_ITEM("deleteItem", "di", "{item-ids}", "hard delete item(s)", ZMailboxUtil.Category.ITEM, 1, 1, new Option[0]), 
/*  400 */     DELETE_IDENTITY("deleteIdentity", "did", "{identity-name}", "delete an identity", ZMailboxUtil.Category.ACCOUNT, 1, 1, new Option[0]), 
/*  401 */     DELETE_INCOMING_FILTER_RULE("deleteFilterRule", "dfrl", "{name}", "delete incoming filter rule", ZMailboxUtil.Category.FILTER, 1, 1, new Option[0]), 
/*  402 */     DELETE_OUTGOING_FILTER_RULE("deleteOutgoingFilterRule", "dofrl", "{name}", "delete outgoing filter rule", ZMailboxUtil.Category.FILTER, 1, 1, new Option[0]), 
/*  403 */     DELETE_FOLDER("deleteFolder", "df", "{folder-path}", "hard delete a folder (and subfolders)", ZMailboxUtil.Category.FOLDER, 1, 1, new Option[0]), 
/*  404 */     DELETE_MESSAGE("deleteMessage", "dm", "{msg-ids}", "hard delete message(s)", ZMailboxUtil.Category.MESSAGE, 1, 1, new Option[0]), 
/*  405 */     DELETE_SIGNATURE("deleteSignature", "dsig", "{signature-name|signature-id}", "delete signature", ZMailboxUtil.Category.ACCOUNT, 1, 1, new Option[0]), 
/*  406 */     DELETE_TAG("deleteTag", "dt", "{tag-name}", "delete a tag", ZMailboxUtil.Category.TAG, 1, 1, new Option[0]), 
/*  407 */     DUMPSTER_DELETE_ITEM("dumpsterDeleteItem", "ddi", "{item-ids}", "permanently delete item(s) from the dumpster", ZMailboxUtil.Category.ITEM, 1, 1, new Option[0]), 
/*  408 */     EMPTY_DUMPSTER("emptyDumpster", null, "", "empty the dumpster", ZMailboxUtil.Category.MISC, 0, 0, new Option[0]), 
/*  409 */     EMPTY_FOLDER("emptyFolder", "ef", "{folder-path}", "empty all the items in a folder (including subfolders)", ZMailboxUtil.Category.FOLDER, 1, 1, new Option[0]), 
/*  410 */     EXIT("exit", "quit", "", "exit program", ZMailboxUtil.Category.MISC, 0, 0, new Option[0]), 
/*  411 */     FLAG_CONTACT("flagContact", "fct", "{contact-ids} [0|1*]", "flag/unflag contact(s)", ZMailboxUtil.Category.CONTACT, 1, 2, new Option[0]), 
/*  412 */     FLAG_CONVERSATION("flagConversation", "fc", "{conv-ids} [0|1*]", "flag/unflag conversation(s)", ZMailboxUtil.Category.CONVERSATION, 1, 2, new Option[0]), 
/*  413 */     FLAG_ITEM("flagItem", "fi", "{item-ids} [0|1*]", "flag/unflag item(s)", ZMailboxUtil.Category.ITEM, 1, 2, new Option[0]), 
/*  414 */     FLAG_MESSAGE("flagMessage", "fm", "{msg-ids} [0|1*]", "flag/unflag message(s)", ZMailboxUtil.Category.MESSAGE, 1, 2, new Option[0]), 
/*  415 */     GET_ALL_CONTACTS("getAllContacts", "gact", "[attr1 [attr2...]]", "get all contacts", ZMailboxUtil.Category.CONTACT, 0, Integer.MAX_VALUE, new Option[] { ZMailboxUtil.O_VERBOSE, ZMailboxUtil.O_FOLDER }), 
/*  416 */     GET_ALL_FOLDERS("getAllFolders", "gaf", "", "get all folders", ZMailboxUtil.Category.FOLDER, 0, 0, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  417 */     GET_ALL_TAGS("getAllTags", "gat", "", "get all tags", ZMailboxUtil.Category.TAG, 0, 0, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  418 */     GET_APPOINTMENT_SUMMARIES("getAppointmentSummaries", "gaps", "{start-date-spec} {end-date-spec} {folder-path}", "get appointment summaries", ZMailboxUtil.Category.APPOINTMENT, 2, 3, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  419 */     GET_CONTACTS("getContacts", "gct", "{contact-ids} [attr1 [attr2...]]", "get contact(s)", ZMailboxUtil.Category.CONTACT, 1, Integer.MAX_VALUE, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  420 */     GET_CONVERSATION("getConversation", "gc", "{conv-id}", "get a converation", ZMailboxUtil.Category.CONVERSATION, 1, 1, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  421 */     GET_IDENTITIES("getIdentities", "gid", "", "get all identites", ZMailboxUtil.Category.ACCOUNT, 0, 0, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  422 */     GET_INCOMING_FILTER_RULES("getFilterRules", "gfrl", "", "get incoming filter rules", ZMailboxUtil.Category.FILTER, 0, 0, new Option[0]), 
/*  423 */     GET_OUTGOING_FILTER_RULES("getOutgoingFilterRules", "gofrl", "", "get outgoing filter rules", ZMailboxUtil.Category.FILTER, 0, 0, new Option[0]), 
/*  424 */     GET_FOLDER("getFolder", "gf", "{folder-path}", "get folder", ZMailboxUtil.Category.FOLDER, 1, 1, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  425 */     GET_FOLDER_REQUEST("getFolderRequest", "gfr", "{folder-id}", "get folder request (always issues a GetFolderRequest)", ZMailboxUtil.Category.FOLDER, 1, 1, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  426 */     GET_FOLDER_GRANT("getFolderGrant", "gfg", "{folder-path}", "get folder grants", ZMailboxUtil.Category.FOLDER, 1, 1, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  427 */     GET_MESSAGE("getMessage", "gm", "{msg-id}", "get a message", ZMailboxUtil.Category.MESSAGE, 1, 1, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  428 */     GET_MAILBOX_SIZE("getMailboxSize", "gms", "", "get mailbox size", ZMailboxUtil.Category.MISC, 0, 0, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  429 */     GET_RIGHTS("getRights", "gr", "[right1 [right2...]]", "get rights currently granted", ZMailboxUtil.Category.RIGHT, 0, Integer.MAX_VALUE, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  430 */     GET_REST_URL("getRestURL", "gru", "{relative-path}", "do a GET on a REST URL relative to the mailbox", ZMailboxUtil.Category.MISC, 1, 1, new Option[] { ZMailboxUtil.O_OUTPUT_FILE, ZMailboxUtil.O_START_TIME, ZMailboxUtil.O_END_TIME, ZMailboxUtil.O_URL }), 
/*      */     
/*  432 */     GET_SIGNATURES("getSignatures", "gsig", "", "get all signatures", ZMailboxUtil.Category.ACCOUNT, 0, 0, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  433 */     GRANT_RIGHT("grantRight", "grr", "{account {name}|group {name}|domain {name}||all|public|guest {email} [{password}]|key {email} [{accesskey}] {[-]right}}", "allow or deny a right to a grantee or a group of grantee. to deny a right, put a '-' in front of the right", ZMailboxUtil.Category.RIGHT, 2, 4, new Option[0]), 
/*  434 */     HELP("help", "?", "commands", "return help on a group of commands, or all commands. Use -v for detailed help.", ZMailboxUtil.Category.MISC, 0, 1, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  435 */     IMPORT_URL_INTO_FOLDER("importURLIntoFolder", "iuif", "{folder-path} {url}", "add the contents to the remote feed at {target-url} to the folder", ZMailboxUtil.Category.FOLDER, 2, 2, new Option[0]), 
/*  436 */     LIST_RIGHTS("listRights", "lr", "", "list and describe all rights that can be granted", ZMailboxUtil.Category.RIGHT, 0, 0, new Option[] { ZMailboxUtil.O_VERBOSE }), 
/*  437 */     MARK_CONVERSATION_READ("markConversationRead", "mcr", "{conv-ids} [0|1*]", "mark conversation(s) as read/unread", ZMailboxUtil.Category.CONVERSATION, 1, 2, new Option[0]), 
/*  438 */     MARK_CONVERSATION_SPAM("markConversationSpam", "mcs", "{conv} [0|1*] [{dest-folder-path}]", "mark conversation as spam/not-spam, and optionally move", ZMailboxUtil.Category.CONVERSATION, 1, 3, new Option[0]), 
/*  439 */     MARK_ITEM_READ("markItemRead", "mir", "{item-ids} [0|1*]", "mark item(s) as read/unread", ZMailboxUtil.Category.ITEM, 1, 2, new Option[0]), 
/*  440 */     MARK_FOLDER_READ("markFolderRead", "mfr", "{folder-path}", "mark all items in a folder as read", ZMailboxUtil.Category.FOLDER, 1, 1, new Option[0]), 
/*  441 */     MARK_MESSAGE_READ("markMessageRead", "mmr", "{msg-ids} [0|1*]", "mark message(s) as read/unread", ZMailboxUtil.Category.MESSAGE, 1, 2, new Option[0]), 
/*  442 */     MARK_MESSAGE_SPAM("markMessageSpam", "mms", "{msg} [0|1*] [{dest-folder-path}]", "mark a message as spam/not-spam, and optionally move", ZMailboxUtil.Category.MESSAGE, 1, 3, new Option[0]), 
/*  443 */     MARK_TAG_READ("markTagRead", "mtr", "{tag-name}", "mark all items with this tag as read", ZMailboxUtil.Category.TAG, 1, 1, new Option[0]), 
/*  444 */     MODIFY_CONTACT("modifyContactAttrs", "mcta", "{contact-id} [attr1 value1 [attr2 value2...]]", "modify a contact", ZMailboxUtil.Category.CONTACT, 3, Integer.MAX_VALUE, new Option[] { ZMailboxUtil.O_REPLACE, ZMailboxUtil.O_IGNORE }), 
/*  445 */     MODIFY_INCOMING_FILTER_RULE("modifyFilterRule", "mfrl", "{name} [*active|inactive] [any|*all] {conditions}+ {actions}+", "modify incoming filter rule", ZMailboxUtil.Category.FILTER, 2, Integer.MAX_VALUE, new Option[0]), 
/*  446 */     MODIFY_OUTGOING_FILTER_RULE("modifyOutgoingFilterRule", "mofrl", "{name} [*active|inactive] [any|*all] {conditions}+ {actions}+", "modify outgoing filter rule", ZMailboxUtil.Category.FILTER, 2, Integer.MAX_VALUE, new Option[0]), 
/*  447 */     MODIFY_FOLDER_CHECKED("modifyFolderChecked", "mfch", "{folder-path} [0|1*]", "modify whether a folder is checked in the UI", ZMailboxUtil.Category.FOLDER, 1, 2, new Option[0]), 
/*  448 */     MODIFY_FOLDER_COLOR("modifyFolderColor", "mfc", "{folder-path} {new-color}", "modify a folder's color", ZMailboxUtil.Category.FOLDER, 2, 2, new Option[0]), 
/*  449 */     MODIFY_FOLDER_EXCLUDE_FREE_BUSY("modifyFolderExcludeFreeBusy", "mfefb", "{folder-path} [0|1*]", "change whether folder is excluded from free-busy", ZMailboxUtil.Category.FOLDER, 1, 2, new Option[0]), 
/*  450 */     MODIFY_FOLDER_FLAGS("modifyFolderFlags", "mff", "{folder-path} {folder-flags}", "replaces the flags on the folder (subscribed, checked, etc.)", ZMailboxUtil.Category.FOLDER, 2, 2, new Option[0]), 
/*  451 */     MODIFY_FOLDER_GRANT("modifyFolderGrant", "mfg", "{folder-path} {account {name}|group {name}|cos {name}|domain {name}|all|public|guest {email}|key {email} [{accesskey}] {permissions|none}}", "add/remove a grant to a folder", ZMailboxUtil.Category.FOLDER, 3, 5, new Option[0]), 
/*  452 */     MODIFY_FOLDER_URL("modifyFolderURL", "mfu", "{folder-path} {url}", "modify a folder's URL", ZMailboxUtil.Category.FOLDER, 2, 2, new Option[0]), 
/*  453 */     MODIFY_IDENTITY("modifyIdentity", "mid", "{identity-name} [attr1 value1 [attr2 value2...]]", "modify an identity", ZMailboxUtil.Category.ACCOUNT, 1, Integer.MAX_VALUE, new Option[0]), 
/*  454 */     MODIFY_ITEM_FLAGS("modifyItemFlags", "mif", "{item-ids} {item-flags}", "replaces the flags on the items (answered, unread, flagged, etc.)", ZMailboxUtil.Category.ITEM, 2, 2, new Option[0]), 
/*  455 */     MODIFY_MOUNTPOINT_ENABLE_SHARED_REMINDER("modifyMountpointEnableSharedReminder", "mmesr", "{mountpoint-path} {0|1}", "enable/disable appointment/task reminder on shared calendar", ZMailboxUtil.Category.FOLDER, 2, 2, new Option[0]), 
/*  456 */     MODIFY_SIGNATURE("modifySignature", "msig", "{signature-name|signature-id} {value}", "modify signature value", ZMailboxUtil.Category.ACCOUNT, 2, 2, new Option[0]), 
/*  457 */     MODIFY_TAG_COLOR("modifyTagColor", "mtc", "{tag-name} {tag-color}", "modify a tag's color", ZMailboxUtil.Category.TAG, 2, 2, new Option[0]), 
/*  458 */     MOVE_CONTACT("moveContact", "mct", "{contact-ids} {dest-folder-path}", "move contact(s) to a new folder", ZMailboxUtil.Category.CONTACT, 2, 2, new Option[0]), 
/*  459 */     MOVE_CONVERSATION("moveConversation", "mc", "{conv-ids} {dest-folder-path}", "move conversation(s) to a new folder", ZMailboxUtil.Category.CONVERSATION, 2, 2, new Option[0]), 
/*  460 */     MOVE_ITEM("moveItem", "mi", "{item-ids} {dest-folder-path}", "move item(s) to a new folder", ZMailboxUtil.Category.ITEM, 2, 2, new Option[0]), 
/*  461 */     MOVE_MESSAGE("moveMessage", "mm", "{msg-ids} {dest-folder-path}", "move message(s) to a new folder", ZMailboxUtil.Category.MESSAGE, 2, 2, new Option[0]), 
/*  462 */     NOOP("noOp", "no", "", "do a NoOp SOAP call to the server", ZMailboxUtil.Category.MISC, 0, 1, new Option[0]), 
/*  463 */     POST_REST_URL("postRestURL", "pru", "{relative-path} {file-name}", "do a POST on a REST URL relative to the mailbox", ZMailboxUtil.Category.MISC, 2, 2, new Option[] { ZMailboxUtil.O_CONTENT_TYPE, ZMailboxUtil.O_IGNORE_ERROR, ZMailboxUtil.O_PRESERVE_ALARMS, ZMailboxUtil.O_URL }), 
/*      */     
/*  465 */     RECOVER_ITEM("recoverItem", "ri", "{item-ids} {dest-folder-path}", "recover item(s) from the dumpster to a folder", ZMailboxUtil.Category.ITEM, 2, 2, new Option[0]), 
/*  466 */     RENAME_FOLDER("renameFolder", "rf", "{folder-path} {new-folder-path}", "rename folder", ZMailboxUtil.Category.FOLDER, 2, 2, new Option[0]), 
/*  467 */     RENAME_SIGNATURE("renameSignature", "rsig", "{signature-name|signature-id} {new-name}", "rename signature", ZMailboxUtil.Category.ACCOUNT, 2, 2, new Option[0]), 
/*  468 */     RENAME_TAG("renameTag", "rt", "{tag-name} {new-tag-name}", "rename tag", ZMailboxUtil.Category.TAG, 2, 2, new Option[0]), 
/*  469 */     REVOKE_RIGHT("revokeRight", "rvr", "{account {name}|group {name}|domain {name}||all|public|guest {email} [{password}]|key {email} [{accesskey}] {[-]right}}", "revoke a right previously granted to a grantee or a group of grantees. to revoke a denied right, put a '-' in front of the right", ZMailboxUtil.Category.RIGHT, 2, 4, new Option[0]), 
/*  470 */     SEARCH("search", "s", "{query}", "perform search", ZMailboxUtil.Category.SEARCH, 0, 1, new Option[] { ZMailboxUtil.O_LIMIT, ZMailboxUtil.O_SORT, ZMailboxUtil.O_TYPES, ZMailboxUtil.O_VERBOSE, ZMailboxUtil.O_CURRENT, ZMailboxUtil.O_NEXT, ZMailboxUtil.O_PREVIOUS, ZMailboxUtil.O_DUMPSTER }), 
/*  471 */     SEARCH_CONVERSATION("searchConv", "sc", "{conv-id} {query}", "perform search on conversation", ZMailboxUtil.Category.SEARCH, 0, 2, new Option[] { ZMailboxUtil.O_LIMIT, ZMailboxUtil.O_SORT, ZMailboxUtil.O_TYPES, ZMailboxUtil.O_VERBOSE, ZMailboxUtil.O_CURRENT, ZMailboxUtil.O_NEXT, ZMailboxUtil.O_PREVIOUS }), 
/*  472 */     SELECT_MAILBOX("selectMailbox", "sm", "{name}", "select a different mailbox. can only be used by an admin", ZMailboxUtil.Category.ADMIN, 1, 1, new Option[] { ZMailboxUtil.O_AUTH, ZMailboxUtil.O_AS_ADMIN }), 
/*  473 */     SYNC_FOLDER("syncFolder", "sf", "{folder-path}", "synchronize folder's contents to the remote feed specified by folder's {url}", ZMailboxUtil.Category.FOLDER, 1, 1, new Option[0]), 
/*  474 */     TAG_CONTACT("tagContact", "tct", "{contact-ids} {tag-name} [0|1*]", "tag/untag contact(s)", ZMailboxUtil.Category.CONTACT, 2, 3, new Option[0]), 
/*  475 */     TAG_CONVERSATION("tagConversation", "tc", "{conv-ids} {tag-name} [0|1*]", "tag/untag conversation(s)", ZMailboxUtil.Category.CONVERSATION, 2, 3, new Option[0]), 
/*  476 */     TAG_ITEM("tagItem", "ti", "{item-ids} {tag-name} [0|1*]", "tag/untag item(s)", ZMailboxUtil.Category.ITEM, 2, 3, new Option[0]), 
/*  477 */     TAG_MESSAGE("tagMessage", "tm", "{msg-ids} {tag-name} [0|1*]", "tag/untag message(s)", ZMailboxUtil.Category.MESSAGE, 2, 3, new Option[0]), 
/*  478 */     WHOAMI("whoami", null, "", "show current auth'd/opened mailbox", ZMailboxUtil.Category.MISC, 0, 0, new Option[0]);
/*      */     
/*      */     private String mName;
/*      */     private String mAlias;
/*      */     private String mSyntax;
/*      */     private String mHelp;
/*      */     private Option[] mOpt;
/*      */     private ZMailboxUtil.Category mCat;
/*  486 */     private int mMinArgLength = 0;
/*  487 */     private int mMaxArgLength = Integer.MAX_VALUE;
/*      */     
/*  489 */     public String getName() { return this.mName; }
/*  490 */     public String getAlias() { return this.mAlias; }
/*  491 */     public String getSyntax() { return this.mSyntax; }
/*  492 */     public String getHelp() { return this.mHelp; }
/*  493 */     public ZMailboxUtil.Category getCategory() { return this.mCat; }
/*  494 */     public boolean hasHelp() { return this.mSyntax != null; }
/*      */     
/*  496 */     public boolean checkArgsLength(String[] args) { int len = args == null ? 0 : args.length;
/*  497 */       return (len >= this.mMinArgLength) && (len <= this.mMaxArgLength);
/*      */     }
/*      */     
/*      */ 
/*      */ 
/*      */     public Options getOptions()
/*      */     {
/*  504 */       Options opts = new Options();
/*  505 */       for (Option o : this.mOpt) {
/*  506 */         opts.addOption(o.getOpt(), o.getLongOpt(), o.hasArg(), o.getDescription());
/*      */       }
/*  508 */       return opts;
/*      */     }
/*      */     
/*      */     public String getCommandHelp()
/*      */     {
/*  513 */       String alias = getAlias();
/*  514 */       String commandName; String commandName; if (alias != null) {
/*  515 */         commandName = String.format("%s(%s)", new Object[] { getName(), alias });
/*      */       } else
/*  517 */         commandName = getName();
/*  518 */       StringBuilder sb = new StringBuilder();
/*  519 */       sb.append(String.format("  %-38s %s%n", new Object[] { commandName, getHelp() }));
/*  520 */       return sb.toString();
/*      */     }
/*      */     
/*      */     public String getFullUsage()
/*      */     {
/*  525 */       String alias = getAlias();
/*  526 */       String commandName; String commandName; if (alias != null) {
/*  527 */         commandName = String.format("%s(%s)", new Object[] { getName(), alias });
/*      */       } else {
/*  529 */         commandName = getName();
/*      */       }
/*      */       
/*  532 */       Collection opts = getOptions().getOptions();
/*      */       
/*  534 */       StringBuilder sb = new StringBuilder();
/*      */       
/*  536 */       sb.append(String.format("  %-28s %s%n", new Object[] { commandName, (opts.size() > 0 ? "[opts] " : "") + getSyntax() }));
/*      */       
/*      */ 
/*      */ 
/*  540 */       for (Object o : opts) {
/*  541 */         Option opt = (Option)o;
/*  542 */         String arg = opt.hasArg() ? " <arg>" : "";
/*  543 */         String shortOpt = opt.getOpt();
/*  544 */         String longOpt = opt.getLongOpt();
/*      */         String optStr;
/*  546 */         String optStr; if (shortOpt != null) {
/*  547 */           optStr = String.format("  -%s/--%s%s", new Object[] { shortOpt, longOpt, arg });
/*      */         } else
/*  549 */           optStr = String.format("  --%s%s", new Object[] { longOpt, arg });
/*  550 */         sb.append(String.format("  %-30s %s%n", new Object[] { optStr, opt.getDescription() }));
/*      */       }
/*      */       
/*  553 */       return sb.toString();
/*      */     }
/*      */     
/*      */     private Command(String name, String alias, String syntax, String help, ZMailboxUtil.Category cat, int minArgLength, int maxArgLength, Option... opts) {
/*  557 */       this.mName = name;
/*  558 */       this.mAlias = ((alias != null) && (alias.length() > 0) ? alias : null);
/*  559 */       this.mSyntax = syntax;
/*  560 */       this.mHelp = help;
/*  561 */       this.mCat = cat;
/*  562 */       this.mMinArgLength = minArgLength;
/*  563 */       this.mMaxArgLength = maxArgLength;
/*  564 */       this.mOpt = opts;
/*      */     }
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */   private String formatSize(long size)
/*      */   {
/*  574 */     if (size > 1073741824L)
/*  575 */       return String.format("%.2f GB", new Object[] { Double.valueOf(size / 1.073741824E9D) });
/*  576 */     if (size > 1048576L)
/*  577 */       return String.format("%.2f MB", new Object[] { Double.valueOf(size / 1048576.0D) });
/*  578 */     if (size > 1024L) {
/*  579 */       return String.format("%.2f KB", new Object[] { Double.valueOf(size / 1024.0D) });
/*      */     }
/*  581 */     return String.format("%d B", new Object[] { Long.valueOf(size) });
/*      */   }
/*      */   
/*      */   private void addCommand(Command command)
/*      */   {
/*  586 */     String name = command.getName().toLowerCase();
/*  587 */     if (this.mCommandIndex.get(name) != null) {
/*  588 */       throw new RuntimeException("duplicate command: " + name);
/*      */     }
/*      */     
/*  591 */     this.mCommandIndex.put(name, command);
/*  592 */     String alias = command.getAlias();
/*  593 */     if (alias != null) {
/*  594 */       alias = alias.toLowerCase();
/*  595 */       if (this.mCommandIndex.get(alias) != null) {
/*  596 */         throw new RuntimeException("duplicate command: " + alias);
/*      */       }
/*  598 */       this.mCommandIndex.put(alias, command);
/*      */     }
/*      */   }
/*      */   
/*      */   private void initCommands() {
/*  603 */     this.mCommandIndex = new HashMap();
/*      */     
/*  605 */     for (Command c : Command.values()) {
/*  606 */       addCommand(c);
/*      */     }
/*      */   }
/*      */   
/*      */   private Command lookupCommand(String command) {
/*  611 */     return (Command)this.mCommandIndex.get(command.toLowerCase());
/*      */   }
/*      */   
/*      */   public ZMailboxUtil() {
/*  615 */     initCommands();
/*      */   }
/*      */   
/*      */   private ZMailbox.Options getMailboxOptions(SoapProvisioning prov, String authAccount, String targetAccount, int lifetimeSeconds)
/*      */     throws ServiceException
/*      */   {
/*  621 */     Key.AccountBy targetBy = StringUtil.isUUID(targetAccount) ? Key.AccountBy.id : Key.AccountBy.name;
/*  622 */     ZMailbox.Options options; ZMailbox.Options options; if (!StringUtil.isNullOrEmpty(authAccount)) {
/*  623 */       Key.AccountBy authBy = StringUtil.isUUID(authAccount) ? Key.AccountBy.id : Key.AccountBy.name;
/*  624 */       SoapAccountInfo sai = prov.getAccountInfo(authBy, authAccount);
/*  625 */       SoapProvisioning.DelegateAuthResponse dar = prov.delegateAuth(authBy, authAccount, lifetimeSeconds > 0 ? lifetimeSeconds : 86400);
/*  626 */       options = new ZMailbox.Options(dar.getAuthToken(), sai.getAdminSoapURL());
/*      */     } else {
/*  628 */       SoapAccountInfo sai = prov.getAccountInfo(targetBy, targetAccount);
/*  629 */       options = new ZMailbox.Options(this.mAdminAuthToken, sai.getAdminSoapURL());
/*      */     }
/*  631 */     options.setTargetAccount(targetAccount);
/*  632 */     options.setTargetAccountBy(targetBy);
/*  633 */     return options;
/*      */   }
/*      */   
/*      */ 
/*      */   public void selectMailbox(String authAccount, SoapProvisioning prov)
/*      */     throws ServiceException
/*      */   {
/*  640 */     selectMailbox(authAccount, authAccount, prov);
/*      */   }
/*      */   
/*      */   public void selectMailbox(String authAccount, String targetAccount, SoapProvisioning prov) throws ServiceException {
/*  644 */     boolean success = false;
/*      */     try {
/*  646 */       if (prov == null)
/*  647 */         throw ZClientException.CLIENT_ERROR("can only select mailbox after adminAuthenticate", null);
/*  648 */       if (this.mProv == null) {
/*  649 */         this.mProv = prov;
/*      */       }
/*  651 */       this.mMbox = null;
/*  652 */       setAuthAccountName(authAccount);
/*  653 */       setTargetAccountName(targetAccount);
/*  654 */       ZMailbox.Options options = getMailboxOptions(prov, authAccount, targetAccount, 86400);
/*  655 */       options.setTimeout(this.mTimeout);
/*      */       
/*  657 */       if (prov.soapGetTransportDebugListener() != null) {
/*  658 */         options.setDebugListener(prov.soapGetTransportDebugListener());
/*      */       } else {
/*  660 */         options.setHttpDebugListener(prov.soapGetHttpTransportDebugListener());
/*      */       }
/*      */       
/*  663 */       this.mMbox = ZMailbox.getMailbox(options);
/*  664 */       dumpMailboxConnect();
/*  665 */       this.mPrompt = String.format("mbox %s> ", new Object[] { this.mMbox.getName() });
/*  666 */       this.mSearchParams = null;
/*  667 */       this.mConvSearchParams = null;
/*  668 */       this.mConvSearchResult = null;
/*  669 */       this.mIndexToId.clear();
/*      */       
/*      */ 
/*  672 */       success = true;
/*      */     } finally {
/*  674 */       if (!success) {
/*  675 */         setAuthAccountName(null);
/*  676 */         setTargetAccountName(null);
/*      */       }
/*      */     }
/*      */   }
/*      */   
/*      */   private void adminAuth(String name, String password, String uri) throws ServiceException {
/*  682 */     this.mAdminAccountName = name;
/*  683 */     this.mPassword = password;
/*  684 */     SoapTransport.DebugListener listener = this.mDebug ? this : null;
/*  685 */     this.mProv = new SoapProvisioning();
/*  686 */     this.mProv.soapSetURI(ZMailbox.resolveUrl(uri, true));
/*  687 */     if (listener != null) {
/*  688 */       this.mProv.soapSetTransportDebugListener(listener);
/*      */     }
/*  690 */     this.mProv.soapAdminAuthenticate(name, password);
/*  691 */     this.mAdminAuthToken = this.mProv.getAuthToken();
/*      */   }
/*      */   
/*      */   private void adminAuth(ZAuthToken zat, String uri) throws ServiceException {
/*  695 */     SoapTransport.DebugListener listener = this.mDebug ? this : null;
/*  696 */     this.mProv = new SoapProvisioning();
/*  697 */     this.mProv.soapSetURI(ZMailbox.resolveUrl(uri, true));
/*  698 */     if (listener != null) {
/*  699 */       this.mProv.soapSetTransportDebugListener(listener);
/*      */     }
/*  701 */     this.mProv.soapAdminAuthenticate(zat);
/*      */   }
/*      */   
/*      */   private void auth(String authAccountName, String password, String targetAccountName, String uri) throws ServiceException {
/*  705 */     boolean success = false;
/*      */     try {
/*  707 */       this.mPassword = password;
/*  708 */       ZMailbox.Options options = new ZMailbox.Options();
/*  709 */       options.setAccount(authAccountName);
/*  710 */       options.setAccountBy(StringUtil.isUUID(authAccountName) ? Key.AccountBy.id : Key.AccountBy.name);
/*  711 */       options.setPassword(this.mPassword);
/*  712 */       options.setTargetAccount(targetAccountName);
/*  713 */       options.setTargetAccountBy(StringUtil.isUUID(targetAccountName) ? Key.AccountBy.id : Key.AccountBy.name);
/*  714 */       options.setUri(ZMailbox.resolveUrl(uri, false));
/*  715 */       options.setDebugListener(this.mDebug ? this : null);
/*  716 */       options.setTimeout(this.mTimeout);
/*  717 */       this.mMbox = ZMailbox.getMailbox(options);
/*  718 */       this.mPrompt = String.format("mbox %s> ", new Object[] { this.mMbox.getName() });
/*  719 */       setAuthAccountName(authAccountName);
/*  720 */       setTargetAccountName(targetAccountName);
/*  721 */       dumpMailboxConnect();
/*  722 */       success = true;
/*      */     } finally {
/*  724 */       if (!success) {
/*  725 */         setAuthAccountName(null);
/*  726 */         setTargetAccountName(null);
/*      */       }
/*      */     }
/*      */   }
/*      */   
/*      */   static class Stats {
/*      */     int numMessages;
/*      */     int numUnread;
/*      */   }
/*      */   
/*      */   private void computeStats(ZFolder f, Stats s) {
/*  737 */     s.numMessages += f.getMessageCount();
/*  738 */     s.numUnread += f.getUnreadCount();
/*  739 */     for (ZFolder c : f.getSubFolders()) {
/*  740 */       computeStats(c, s);
/*      */     }
/*      */   }
/*      */   
/*      */   private void dumpMailboxConnect() throws ServiceException {
/*  745 */     if (!this.mInteractive) return;
/*  746 */     if (StringUtil.isNullOrEmpty(this.mTargetAccountName)) {
/*  747 */       stdout.format("no mailbox opened%n", new Object[0]);
/*  748 */       if (!StringUtil.isNullOrEmpty(this.mAdminAccountName)) {
/*  749 */         stdout.format("authenticated as %s (admin)%n", new Object[] { this.mAdminAccountName });
/*      */       } else {
/*  751 */         stdout.format("not authenticated%n", new Object[0]);
/*      */       }
/*  753 */       return;
/*      */     }
/*  755 */     Stats s = new Stats();
/*  756 */     computeStats(this.mMbox.getUserRoot(), s);
/*  757 */     stdout.format("mailbox: %s, size: %s, messages: %d, unread: %d%n", new Object[] { this.mMbox.getName(), formatSize(this.mMbox.getSize()), Integer.valueOf(s.numMessages), Integer.valueOf(s.numUnread) });
/*      */     
/*      */ 
/*      */ 
/*      */ 
/*  762 */     if ((StringUtil.equalIgnoreCase(this.mTargetAccountName, this.mAuthAccountName)) || (!StringUtil.isNullOrEmpty(this.mAuthAccountName)))
/*      */     {
/*  764 */       stdout.format("authenticated as %s%n", new Object[] { this.mAuthAccountName });
/*      */     } else {
/*  766 */       stdout.format("authenticated as %s (admin)%n", new Object[] { this.mAdminAccountName });
/*      */     }
/*      */   }
/*      */   
/*      */   public void initMailbox() throws ServiceException {
/*  771 */     if ((this.mPassword == null) && (this.mAdminAuthToken == null)) {
/*  772 */       return;
/*      */     }
/*  774 */     if (this.mAdminAccountName != null) {
/*  775 */       adminAuth(this.mAdminAccountName, this.mPassword, this.mUrl);
/*  776 */     } else if (this.mAdminAuthToken != null) {
/*  777 */       adminAuth(this.mAdminAuthToken, this.mUrl);
/*      */     }
/*      */     
/*  780 */     if (this.mTargetAccountName == null) {
/*  781 */       this.mAuthAccountName = null;
/*  782 */       return;
/*      */     }
/*      */     
/*  785 */     if (this.mAdminAccountName != null) {
/*  786 */       selectMailbox(this.mAuthAccountName, this.mTargetAccountName, this.mProv);
/*      */     } else {
/*  788 */       auth(this.mAuthAccountName, this.mPassword, this.mTargetAccountName, this.mUrl);
/*      */     }
/*      */   }
/*      */   
/*      */   private ZTag lookupTag(String idOrName) throws ServiceException {
/*  793 */     ZTag tag = this.mMbox.getTagByName(idOrName);
/*  794 */     if (tag == null) {
/*  795 */       tag = this.mMbox.getTagById(idOrName);
/*      */     }
/*  797 */     if (tag == null) {
/*  798 */       throw ZClientException.CLIENT_ERROR("unknown tag: " + idOrName, null);
/*      */     }
/*  800 */     return tag;
/*      */   }
/*      */   
/*      */ 
/*      */   private static final long MBYTES = 1048576L;
/*      */   
/*      */   private static final long GBYTES = 1073741824L;
/*      */   
/*      */   private String lookupTagIds(String idsOrNames)
/*      */     throws ServiceException
/*      */   {
/*  811 */     StringBuilder ids = new StringBuilder();
/*  812 */     for (String t : idsOrNames.split(",")) {
/*  813 */       ZTag tag = lookupTag(t);
/*  814 */       if (ids.length() > 0) {
/*  815 */         ids.append(",");
/*      */       }
/*  817 */       ids.append(tag.getId());
/*      */     }
/*  819 */     return ids.toString();
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */   private String lookupTagNames(String ids)
/*      */     throws ServiceException
/*      */   {
/*  827 */     StringBuilder names = new StringBuilder();
/*  828 */     for (String tid : ids.split(",")) {
/*  829 */       ZTag tag = lookupTag(tid);
/*  830 */       if (names.length() > 0) {
/*  831 */         names.append(", ");
/*      */       }
/*  833 */       names.append(tag == null ? tid : tag.getName());
/*      */     }
/*  835 */     return names.toString();
/*      */   }
/*      */   
/*      */   private String lookupFolderId(String pathOrId) throws ServiceException {
/*  839 */     return lookupFolderId(pathOrId, false);
/*      */   }
/*      */   
/*  842 */   Pattern sTargetConstraint = Pattern.compile("\\{(.*)\\}$");
/*      */   
/*      */   private String id(String indexOrId) throws ServiceException {
/*  845 */     Matcher m = this.sTargetConstraint.matcher(indexOrId);
/*  846 */     if (m.find()) {
/*  847 */       indexOrId = m.replaceAll("");
/*      */     }
/*      */     
/*  850 */     StringBuilder ids = new StringBuilder();
/*  851 */     for (String t : indexOrId.split(",")) {
/*  852 */       if ((t.length() > 1) && (t.charAt(0) == '#')) {
/*  853 */         t = t.substring(1);
/*      */         
/*  855 */         int i = t.indexOf('-');
/*  856 */         if (i != -1) {
/*  857 */           int start = Integer.parseInt(t.substring(0, i));
/*  858 */           int end = Integer.parseInt(t.substring(i + 1, t.length()));
/*  859 */           for (int j = start; j <= end; j++) {
/*  860 */             String id = (String)this.mIndexToId.get(Integer.valueOf(j));
/*  861 */             if (id == null) {
/*  862 */               throw ZClientException.CLIENT_ERROR("unknown index: " + t, null);
/*      */             }
/*  864 */             if (ids.length() > 0) {
/*  865 */               ids.append(",");
/*      */             }
/*  867 */             ids.append(id);
/*      */           }
/*      */         } else {
/*  870 */           String id = (String)this.mIndexToId.get(Integer.valueOf(Integer.parseInt(t)));
/*  871 */           if (id == null) {
/*  872 */             throw ZClientException.CLIENT_ERROR("unknown index: " + t, null);
/*      */           }
/*  874 */           if (ids.length() > 0) {
/*  875 */             ids.append(",");
/*      */           }
/*  877 */           ids.append(id);
/*      */         }
/*      */       } else {
/*  880 */         if (ids.length() > 0) {
/*  881 */           ids.append(",");
/*      */         }
/*  883 */         ids.append(t);
/*      */       }
/*      */     }
/*  886 */     return ids.toString();
/*      */   }
/*      */   
/*      */   private String lookupFolderId(String pathOrId, boolean parent) throws ServiceException {
/*  890 */     if ((parent) && (pathOrId != null)) {
/*  891 */       pathOrId = ZMailbox.getParentPath(pathOrId);
/*      */     }
/*  893 */     if ((pathOrId == null) || (pathOrId.length() == 0)) {
/*  894 */       return null;
/*      */     }
/*  896 */     ZFolder folder = this.mMbox.getFolderById(pathOrId);
/*  897 */     if (folder == null) {
/*  898 */       folder = this.mMbox.getFolderByPath(pathOrId);
/*      */     }
/*  900 */     if (folder == null) {
/*  901 */       throw ZClientException.CLIENT_ERROR("unknown folder: " + pathOrId, null);
/*      */     }
/*  903 */     return folder.getId();
/*      */   }
/*      */   
/*      */   private ZFolder lookupFolder(String pathOrId) throws ServiceException {
/*  907 */     if ((pathOrId == null) || (pathOrId.length() == 0)) {
/*  908 */       return null;
/*      */     }
/*  910 */     ZFolder folder = this.mMbox.getFolderById(pathOrId);
/*  911 */     if (folder == null) {
/*  912 */       folder = this.mMbox.getFolderByPath(pathOrId);
/*      */     }
/*  914 */     if (folder == null) {
/*  915 */       throw ZClientException.CLIENT_ERROR("unknown folder: " + pathOrId, null);
/*      */     }
/*  917 */     return folder;
/*      */   }
/*      */   
/*      */   private String param(String[] args, int index, String defaultValue) {
/*  921 */     return args.length > index ? args[index] : defaultValue;
/*      */   }
/*      */   
/*      */   private boolean paramb(String[] args, int index, boolean defaultValue) {
/*  925 */     return args.length > index ? args[index].equals("1") : defaultValue;
/*      */   }
/*      */   
/*      */   private String param(String[] args, int index) {
/*  929 */     return param(args, index, null);
/*      */   }
/*      */   
/*      */   private ZTag.Color tagColorOpt() throws ServiceException {
/*  933 */     String color = this.mCommandLine.getOptionValue(O_COLOR.getOpt());
/*  934 */     return color == null ? null : ZTag.Color.fromString(color);
/*      */   }
/*      */   
/*      */   private String tagsOpt() throws ServiceException {
/*  938 */     String tags = this.mCommandLine.getOptionValue(O_TAGS.getOpt());
/*  939 */     return tags == null ? null : lookupTagIds(tags);
/*      */   }
/*      */   
/*      */   private ZFolder.Color folderColorOpt() throws ServiceException {
/*  943 */     String color = this.mCommandLine.getOptionValue(O_COLOR.getOpt());
/*  944 */     return color == null ? null : ZFolder.Color.fromString(color);
/*      */   }
/*      */   
/*      */   private ZFolder.View folderViewOpt() {
/*  948 */     String view = this.mCommandLine.getOptionValue(O_VIEW.getOpt());
/*  949 */     return view == null ? null : ZFolder.View.fromString(view);
/*      */   }
/*      */   
/*      */   private String flagsOpt() {
/*  953 */     return this.mCommandLine.getOptionValue(O_FLAGS.getOpt());
/*      */   }
/*      */   
/*      */   private String urlOpt(boolean admin) {
/*  957 */     String url = this.mCommandLine.getOptionValue(O_URL.getOpt());
/*  958 */     return (url == null) && (admin) ? this.mUrl : url;
/*      */   }
/*      */   
/*      */   private String outputFileOpt() {
/*  962 */     return this.mCommandLine.getOptionValue(O_OUTPUT_FILE.getOpt());
/*      */   }
/*      */   
/*      */   private String contentTypeOpt() {
/*  966 */     return this.mCommandLine.getOptionValue(O_CONTENT_TYPE.getOpt());
/*      */   }
/*      */   
/*      */   private boolean ignoreAndContinueOnErrorOpt() {
/*  970 */     return this.mCommandLine.hasOption(O_IGNORE_ERROR.getOpt());
/*      */   }
/*      */   
/*      */   private boolean preserveAlarmsOpt() {
/*  974 */     return this.mCommandLine.hasOption(O_PRESERVE_ALARMS.getLongOpt());
/*      */   }
/*      */   
/*      */   private String startTimeOpt() {
/*  978 */     return this.mCommandLine.getOptionValue(O_START_TIME.getLongOpt());
/*      */   }
/*      */   
/*      */   private String endTimeOpt() {
/*  982 */     return this.mCommandLine.getOptionValue(O_END_TIME.getLongOpt());
/*      */   }
/*      */   
/*      */   private String typesOpt() throws ServiceException {
/*  986 */     String t = this.mCommandLine.getOptionValue(O_TYPES.getOpt());
/*  987 */     return t == null ? null : ZSearchParams.getCanonicalTypes(t);
/*      */   }
/*      */   
/*      */   private long dateOpt(long def) {
/*  991 */     String ds = this.mCommandLine.getOptionValue(O_DATE.getOpt());
/*  992 */     return ds == null ? def : Long.parseLong(ds);
/*      */   }
/*      */   
/*      */   private String folderOpt() {
/*  996 */     return this.mCommandLine.getOptionValue(O_FOLDER.getOpt());
/*      */   }
/*      */   
/*      */   private boolean ignoreOpt() {
/* 1000 */     return this.mCommandLine.hasOption(O_IGNORE.getOpt());
/*      */   }
/*      */   
/*      */   private boolean verboseOpt() {
/* 1004 */     return this.mCommandLine.hasOption(O_VERBOSE.getOpt());
/*      */   }
/*      */   
/* 1007 */   private boolean currrentOpt() { return this.mCommandLine.hasOption(O_CURRENT.getOpt()); }
/*      */   
/* 1009 */   private boolean nextOpt() { return this.mCommandLine.hasOption(O_NEXT.getOpt()); }
/*      */   
/* 1011 */   private boolean previousOpt() { return this.mCommandLine.hasOption(O_PREVIOUS.getOpt()); }
/*      */   
/* 1013 */   private boolean firstOpt() { return this.mCommandLine.hasOption(O_FIRST.getOpt()); }
/*      */   
/* 1015 */   private String beforeOpt() { return this.mCommandLine.getOptionValue(O_BEFORE.getOpt()); }
/*      */   
/* 1017 */   private String afterOpt() { return this.mCommandLine.getOptionValue(O_AFTER.getOpt()); }
/*      */   
/*      */   private SearchSortBy searchSortByOpt() throws ServiceException {
/* 1020 */     String sort = this.mCommandLine.getOptionValue(O_SORT.getOpt());
/* 1021 */     return sort == null ? null : SearchSortBy.fromString(sort);
/*      */   }
/*      */   
/*      */ 
/* 1025 */   private boolean validateOpt() { return !this.mCommandLine.hasOption(O_NO_VALIDATION.getLongOpt()); }
/*      */   
/*      */   static enum ExecuteStatus {
/* 1028 */     OK,  EXIT;
/*      */     
/*      */     private ExecuteStatus() {} }
/* 1031 */   public ExecuteStatus execute(String[] argsIn) throws ServiceException, IOException { this.mCommand = lookupCommand(argsIn[0]);
/*      */     
/*      */ 
/* 1034 */     String[] args = new String[argsIn.length - 1];
/* 1035 */     System.arraycopy(argsIn, 1, args, 0, args.length);
/*      */     
/* 1037 */     if (this.mCommand == null) {
/* 1038 */       throw ZClientException.CLIENT_ERROR("Unknown command: (" + argsIn[0] + ") Type: 'help commands' for a list", null);
/*      */     }
/*      */     try {
/* 1041 */       this.mCommandLine = this.mParser.parse(this.mCommand.getOptions(), args, true);
/* 1042 */       args = this.mCommandLine.getArgs();
/*      */     } catch (ParseException e) {
/* 1044 */       usage();
/* 1045 */       return ExecuteStatus.OK;
/*      */     }
/*      */     
/* 1048 */     if (!this.mCommand.checkArgsLength(args)) {
/* 1049 */       usage();
/* 1050 */       return ExecuteStatus.OK;
/*      */     }
/*      */     
/* 1053 */     if ((this.mCommand != Command.EXIT) && (this.mCommand != Command.HELP) && (this.mCommand != Command.AUTHENTICATE) && (this.mCommand != Command.ADMIN_AUTHENTICATE) && (this.mCommand != Command.SELECT_MAILBOX) && (this.mCommand != Command.WHOAMI))
/*      */     {
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/* 1061 */       if (this.mMbox == null) {
/* 1062 */         throw ZClientException.CLIENT_ERROR("no mailbox opened. select one with authenticate/adminAuthenticate/selectMailbox", null);
/*      */       }
/*      */     }
/*      */     
/* 1066 */     switch (this.mCommand) {
/*      */     case AUTO_COMPLETE: 
/* 1068 */       doAutoComplete(args);
/* 1069 */       break;
/*      */     case AUTO_COMPLETE_GAL: 
/* 1071 */       doAutoCompleteGal(args);
/* 1072 */       break;
/*      */     case AUTHENTICATE: 
/* 1074 */       doAuth(args);
/* 1075 */       break;
/*      */     case ADD_INCOMING_FILTER_RULE: 
/* 1077 */       doAddIncomingFilterRule(args);
/* 1078 */       break;
/*      */     case ADD_OUTGOING_FILTER_RULE: 
/* 1080 */       doAddOutgoingFilterRule(args);
/* 1081 */       break;
/*      */     case ADD_MESSAGE: 
/* 1083 */       doAddMessage(args);
/* 1084 */       break;
/*      */     case ADMIN_AUTHENTICATE: 
/* 1086 */       doAdminAuth(args);
/* 1087 */       break;
/*      */     case CHECK_RIGHT: 
/* 1089 */       doCheckRight(args);
/* 1090 */       break;
/*      */     case CREATE_CONTACT: 
/* 1092 */       String ccId = this.mMbox.createContact(lookupFolderId(folderOpt()), tagsOpt(), getContactMap(args, 0, !ignoreOpt())).getId();
/* 1093 */       stdout.println(ccId);
/* 1094 */       break;
/*      */     case CREATE_IDENTITY: 
/* 1096 */       this.mMbox.createIdentity(new ZIdentity(args[0], getMultiMap(args, 1)));
/* 1097 */       break;
/*      */     case CREATE_FOLDER: 
/* 1099 */       doCreateFolder(args);
/* 1100 */       break;
/*      */     case CREATE_MOUNTPOINT: 
/* 1102 */       doCreateMountpoint(args);
/* 1103 */       break;
/*      */     case CREATE_SEARCH_FOLDER: 
/* 1105 */       doCreateSearchFolder(args);
/* 1106 */       break;
/*      */     case CREATE_SIGNATURE: 
/* 1108 */       doCreateSignature(args);
/* 1109 */       break;
/*      */     case CREATE_TAG: 
/* 1111 */       ZTag ct = this.mMbox.createTag(args[0], tagColorOpt());
/* 1112 */       stdout.println(ct.getId());
/* 1113 */       break;
/*      */     case DELETE_CONTACT: 
/* 1115 */       this.mMbox.deleteContact(args[0]);
/* 1116 */       break;
/*      */     case DELETE_CONVERSATION: 
/* 1118 */       this.mMbox.deleteConversation(id(args[0]), param(args, 1));
/* 1119 */       break;
/*      */     case DELETE_INCOMING_FILTER_RULE: 
/* 1121 */       doDeleteIncomingFilterRule(args);
/* 1122 */       break;
/*      */     case DELETE_OUTGOING_FILTER_RULE: 
/* 1124 */       doDeleteOutgoingFilterRule(args);
/* 1125 */       break;
/*      */     case DELETE_FOLDER: 
/* 1127 */       this.mMbox.deleteFolder(lookupFolderId(args[0]));
/* 1128 */       break;
/*      */     case DELETE_IDENTITY: 
/* 1130 */       this.mMbox.deleteIdentity(args[0]);
/* 1131 */       break;
/*      */     case DELETE_ITEM: 
/* 1133 */       this.mMbox.deleteItem(id(args[0]), param(args, 1));
/* 1134 */       break;
/*      */     case DELETE_MESSAGE: 
/* 1136 */       this.mMbox.deleteMessage(id(args[0]));
/* 1137 */       break;
/*      */     case DELETE_SIGNATURE: 
/* 1139 */       this.mMbox.deleteSignature(lookupSignatureId(args[0]));
/* 1140 */       break;
/*      */     case DELETE_TAG: 
/* 1142 */       this.mMbox.deleteTag(lookupTag(args[0]).getId());
/* 1143 */       break;
/*      */     case DUMPSTER_DELETE_ITEM: 
/* 1145 */       this.mMbox.dumpsterDeleteItem(id(args[0]));
/* 1146 */       break;
/*      */     case EMPTY_DUMPSTER: 
/* 1148 */       this.mMbox.emptyDumpster();
/* 1149 */       break;
/*      */     case EMPTY_FOLDER: 
/* 1151 */       this.mMbox.emptyFolder(lookupFolderId(args[0]));
/* 1152 */       break;
/*      */     case EXIT: 
/* 1154 */       return ExecuteStatus.EXIT;
/*      */     
/*      */     case FLAG_CONTACT: 
/* 1157 */       this.mMbox.flagContact(id(args[0]), paramb(args, 1, true));
/* 1158 */       break;
/*      */     case FLAG_CONVERSATION: 
/* 1160 */       this.mMbox.flagConversation(id(args[0]), paramb(args, 1, true), param(args, 2));
/* 1161 */       break;
/*      */     case FLAG_ITEM: 
/* 1163 */       this.mMbox.flagItem(id(args[0]), paramb(args, 1, true), param(args, 2));
/* 1164 */       break;
/*      */     case FLAG_MESSAGE: 
/* 1166 */       this.mMbox.flagMessage(id(args[0]), paramb(args, 1, true));
/* 1167 */       break;
/*      */     case GET_ALL_CONTACTS: 
/* 1169 */       doGetAllContacts(args);
/* 1170 */       break;
/*      */     case GET_CONTACTS: 
/* 1172 */       doGetContacts(args);
/* 1173 */       break;
/*      */     case GET_IDENTITIES: 
/* 1175 */       doGetIdentities();
/* 1176 */       break;
/*      */     case GET_SIGNATURES: 
/* 1178 */       doGetSignatures();
/* 1179 */       break;
/*      */     case GET_ALL_FOLDERS: 
/* 1181 */       doGetAllFolders();
/* 1182 */       break;
/*      */     case GET_ALL_TAGS: 
/* 1184 */       doGetAllTags();
/* 1185 */       break;
/*      */     case GET_APPOINTMENT_SUMMARIES: 
/* 1187 */       doGetAppointmentSummaries(args);
/* 1188 */       break;
/*      */     case GET_CONVERSATION: 
/* 1190 */       doGetConversation(args);
/* 1191 */       break;
/*      */     case GET_INCOMING_FILTER_RULES: 
/* 1193 */       doGetIncomingFilterRules();
/* 1194 */       break;
/*      */     case GET_OUTGOING_FILTER_RULES: 
/* 1196 */       doGetOutgoingFilterRules();
/* 1197 */       break;
/*      */     case GET_FOLDER: 
/* 1199 */       doGetFolder(args);
/* 1200 */       break;
/*      */     case GET_FOLDER_REQUEST: 
/* 1202 */       doGetFolderRequest(args);
/* 1203 */       break;
/*      */     case GET_FOLDER_GRANT: 
/* 1205 */       doGetFolderGrant(args);
/* 1206 */       break;
/*      */     case GET_MAILBOX_SIZE: 
/* 1208 */       if (verboseOpt()) stdout.format("%d%n", new Object[] { Long.valueOf(this.mMbox.getSize()) }); else
/* 1209 */         stdout.format("%s%n", new Object[] { formatSize(this.mMbox.getSize()) });
/* 1210 */       break;
/*      */     case GET_MESSAGE: 
/* 1212 */       doGetMessage(args);
/* 1213 */       break;
/*      */     case GET_RIGHTS: 
/* 1215 */       doGetRights(args);
/* 1216 */       break;
/*      */     case GET_REST_URL: 
/* 1218 */       doGetRestURL(args);
/* 1219 */       break;
/*      */     case GRANT_RIGHT: 
/* 1221 */       doGrantRight(args);
/* 1222 */       break;
/*      */     case HELP: 
/* 1224 */       doHelp(args);
/* 1225 */       break;
/*      */     case IMPORT_URL_INTO_FOLDER: 
/* 1227 */       this.mMbox.importURLIntoFolder(lookupFolderId(args[0]), args[1]);
/* 1228 */       break;
/*      */     case LIST_RIGHTS: 
/* 1230 */       doListRights();
/* 1231 */       break;
/*      */     case MARK_CONVERSATION_READ: 
/* 1233 */       this.mMbox.markConversationRead(id(args[0]), paramb(args, 1, true), param(args, 2));
/* 1234 */       break;
/*      */     case MARK_ITEM_READ: 
/* 1236 */       this.mMbox.markItemRead(id(args[0]), paramb(args, 1, true), param(args, 2));
/* 1237 */       break;
/*      */     case MARK_FOLDER_READ: 
/* 1239 */       this.mMbox.markFolderRead(lookupFolderId(args[0]));
/* 1240 */       break;
/*      */     case MARK_MESSAGE_READ: 
/* 1242 */       this.mMbox.markMessageRead(id(args[0]), paramb(args, 1, true));
/* 1243 */       break;
/*      */     case MARK_CONVERSATION_SPAM: 
/* 1245 */       this.mMbox.markConversationSpam(id(args[0]), paramb(args, 1, true), lookupFolderId(param(args, 2)), param(args, 3));
/* 1246 */       break;
/*      */     case MARK_MESSAGE_SPAM: 
/* 1248 */       this.mMbox.markMessageSpam(id(args[0]), paramb(args, 1, true), lookupFolderId(param(args, 2)));
/* 1249 */       break;
/*      */     case MARK_TAG_READ: 
/* 1251 */       this.mMbox.markTagRead(lookupTag(args[0]).getId());
/* 1252 */       break;
/*      */     case MODIFY_CONTACT: 
/* 1254 */       doModifyContact(args);
/* 1255 */       break;
/*      */     case MODIFY_INCOMING_FILTER_RULE: 
/* 1257 */       doModifyIncomingFilterRule(args);
/* 1258 */       break;
/*      */     case MODIFY_OUTGOING_FILTER_RULE: 
/* 1260 */       doModifyOutgoingFilterRule(args);
/* 1261 */       break;
/*      */     case MODIFY_FOLDER_CHECKED: 
/* 1263 */       this.mMbox.modifyFolderChecked(lookupFolderId(args[0]), paramb(args, 1, true));
/* 1264 */       break;
/*      */     case MODIFY_FOLDER_COLOR: 
/* 1266 */       this.mMbox.modifyFolderColor(lookupFolderId(args[0]), ZFolder.Color.fromString(args[1]));
/* 1267 */       break;
/*      */     case MODIFY_FOLDER_EXCLUDE_FREE_BUSY: 
/* 1269 */       this.mMbox.modifyFolderExcludeFreeBusy(lookupFolderId(args[0]), paramb(args, 1, true));
/* 1270 */       break;
/*      */     case MODIFY_FOLDER_GRANT: 
/* 1272 */       doModifyFolderGrant(args);
/* 1273 */       break;
/*      */     case MODIFY_FOLDER_FLAGS: 
/* 1275 */       this.mMbox.updateFolder(lookupFolderId(args[0]), null, null, null, null, args[1], null);
/* 1276 */       break;
/*      */     case MODIFY_FOLDER_URL: 
/* 1278 */       this.mMbox.modifyFolderURL(lookupFolderId(args[0]), args[1]);
/* 1279 */       break;
/*      */     case MODIFY_IDENTITY: 
/* 1281 */       this.mMbox.modifyIdentity(new ZIdentity(args[0], getMultiMap(args, 1)));
/* 1282 */       break;
/*      */     case MODIFY_ITEM_FLAGS: 
/* 1284 */       this.mMbox.updateItem(id(args[0]), null, null, args[1], null);
/* 1285 */       break;
/*      */     case MODIFY_MOUNTPOINT_ENABLE_SHARED_REMINDER: 
/* 1287 */       this.mMbox.enableSharedReminder(lookupFolderId(args[0]), paramb(args, 1, false));
/* 1288 */       break;
/*      */     case MODIFY_SIGNATURE: 
/* 1290 */       doModifySignature(args);
/* 1291 */       break;
/*      */     case MODIFY_TAG_COLOR: 
/* 1293 */       this.mMbox.modifyTagColor(lookupTag(args[0]).getId(), ZTag.Color.fromString(args[1]));
/* 1294 */       break;
/*      */     case MOVE_CONVERSATION: 
/* 1296 */       this.mMbox.moveConversation(id(args[0]), lookupFolderId(param(args, 1)), param(args, 2));
/* 1297 */       break;
/*      */     case MOVE_ITEM: 
/* 1299 */       this.mMbox.moveItem(id(args[0]), lookupFolderId(param(args, 1)), param(args, 2));
/* 1300 */       break;
/*      */     case MOVE_MESSAGE: 
/* 1302 */       this.mMbox.moveMessage(id(args[0]), lookupFolderId(param(args, 1)));
/* 1303 */       break;
/*      */     case MOVE_CONTACT: 
/* 1305 */       this.mMbox.moveContact(id(args[0]), lookupFolderId(param(args, 1)));
/* 1306 */       break;
/*      */     case NOOP: 
/* 1308 */       doNoop(args);
/* 1309 */       break;
/*      */     case POST_REST_URL: 
/* 1311 */       doPostRestURL(args);
/* 1312 */       break;
/*      */     case RECOVER_ITEM: 
/* 1314 */       this.mMbox.recoverItem(id(args[0]), lookupFolderId(param(args, 1)));
/* 1315 */       break;
/*      */     case RENAME_FOLDER: 
/* 1317 */       this.mMbox.renameFolder(lookupFolderId(args[0]), args[1]);
/* 1318 */       break;
/*      */     case RENAME_SIGNATURE: 
/* 1320 */       doRenameSignature(args);
/* 1321 */       break;
/*      */     case RENAME_TAG: 
/* 1323 */       this.mMbox.renameTag(lookupTag(args[0]).getId(), args[1]);
/* 1324 */       break;
/*      */     case REVOKE_RIGHT: 
/* 1326 */       doRevokeRight(args);
/* 1327 */       break;
/*      */     case SEARCH: 
/* 1329 */       doSearch(args);
/* 1330 */       break;
/*      */     case SEARCH_CONVERSATION: 
/* 1332 */       doSearchConv(args);
/* 1333 */       break;
/*      */     case SELECT_MAILBOX: 
/* 1335 */       doSelectMailbox(args);
/* 1336 */       break;
/*      */     case SYNC_FOLDER: 
/* 1338 */       this.mMbox.syncFolder(lookupFolderId(args[0]));
/* 1339 */       break;
/*      */     case TAG_CONTACT: 
/* 1341 */       this.mMbox.tagContact(id(args[0]), lookupTag(args[1]).getId(), paramb(args, 2, true));
/* 1342 */       break;
/*      */     case TAG_CONVERSATION: 
/* 1344 */       this.mMbox.tagConversation(id(args[0]), lookupTag(args[1]).getId(), paramb(args, 2, true), param(args, 3));
/* 1345 */       break;
/*      */     case TAG_ITEM: 
/* 1347 */       this.mMbox.tagItem(id(args[0]), lookupTag(args[1]).getId(), paramb(args, 2, true), param(args, 3));
/* 1348 */       break;
/*      */     case TAG_MESSAGE: 
/* 1350 */       this.mMbox.tagMessage(id(args[0]), lookupTag(args[1]).getId(), paramb(args, 2, true));
/* 1351 */       break;
/*      */     case WHOAMI: 
/* 1353 */       dumpMailboxConnect();
/* 1354 */       break;
/*      */     default: 
/* 1356 */       throw ZClientException.CLIENT_ERROR("Unhandled command: (" + this.mCommand.name() + ")", null);
/*      */     }
/* 1358 */     return ExecuteStatus.OK;
/*      */   }
/*      */   
/* 1361 */   private final ZEventHandler mTraceHandler = new TraceHandler(null);
/*      */   private static PrintWriter stdout;
/*      */   private static PrintWriter stderr;
/*      */   
/*      */   private static class TraceHandler extends ZEventHandler {
/* 1366 */     public void handleRefresh(ZRefreshEvent refreshEvent, ZMailbox mailbox) { ZMailboxUtil.stdout.println("ZRefreshEvent: " + refreshEvent); }
/*      */     
/*      */     public void handleModify(ZModifyEvent event, ZMailbox mailbox)
/*      */     {
/* 1370 */       ZMailboxUtil.stdout.println(event.getClass().getSimpleName() + ": " + event);
/*      */     }
/*      */     
/*      */     public void handleCreate(ZCreateEvent event, ZMailbox mailbox) {
/* 1374 */       ZMailboxUtil.stdout.println(event.getClass().getSimpleName() + ": " + event);
/*      */     }
/*      */     
/*      */     public void handleDelete(ZDeleteEvent event, ZMailbox mailbox) {
/* 1378 */       ZMailboxUtil.stdout.println("ZDeleteEvent: " + event);
/*      */     }
/*      */   }
/*      */   
/*      */   private void doNoop(String[] args) throws ServiceException {
/* 1383 */     if ((args.length == 0) || (!args[0].equals("-t"))) {
/* 1384 */       this.mMbox.noOp();
/*      */     } else {
/* 1386 */       this.mMbox.addEventHandler(this.mTraceHandler);
/*      */       for (;;) {
/* 1388 */         stdout.println("NoOp: " + DateUtil.toGeneralizedTime(new Date()));
/* 1389 */         this.mMbox.noOp();
/*      */         try {
/* 1391 */           Thread.sleep(5000L);
/*      */         }
/*      */         catch (InterruptedException e) {
/* 1394 */           e.printStackTrace();
/*      */         }
/*      */       }
/*      */     }
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */   private static Session mSession;
/*      */   
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */   String mConvSearchConvId;
/*      */   
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */   private long mSendStart;
/*      */   
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */   private void doGetAppointmentSummaries(String[] args)
/*      */     throws ServiceException
/*      */   {
/* 1442 */     long startTime = DateUtil.parseDateSpecifier(args[0], new Date().getTime());
/* 1443 */     long endTime = DateUtil.parseDateSpecifier(args[1], new Date().getTime() + 604800000L);
/* 1444 */     String folderId = args.length == 3 ? lookupFolderId(args[2]) : null;
/* 1445 */     List<ZMailbox.ZApptSummaryResult> results = this.mMbox.getApptSummaries(null, startTime, endTime, new String[] { folderId }, TimeZone.getDefault(), "appointment");
/* 1446 */     if (results.size() != 1) return;
/* 1447 */     ZMailbox.ZApptSummaryResult result = (ZMailbox.ZApptSummaryResult)results.get(0);
/*      */     
/* 1449 */     stdout.print("[");
/* 1450 */     boolean first = true;
/* 1451 */     for (ZAppointmentHit appt : result.getAppointments()) {
/* 1452 */       if (!first) stdout.println(",");
/* 1453 */       stdout.print(ZJSONObject.toString(appt));
/* 1454 */       if (first) first = false;
/*      */     }
/* 1456 */     stdout.println("]");
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */   private void doAddIncomingFilterRule(String[] args)
/*      */     throws ServiceException
/*      */   {
/* 1470 */     ZFilterRules rules = this.mMbox.getIncomingFilterRules();
/* 1471 */     doAddFilterRule(args, rules);
/* 1472 */     this.mMbox.saveIncomingFilterRules(rules);
/*      */   }
/*      */   
/*      */   private void doAddOutgoingFilterRule(String[] args) throws ServiceException {
/* 1476 */     ZFilterRules rules = this.mMbox.getOutgoingFilterRules();
/* 1477 */     doAddFilterRule(args, rules);
/* 1478 */     this.mMbox.saveOutgoingFilterRules(rules);
/*      */   }
/*      */   
/*      */   private void doAddFilterRule(String[] args, ZFilterRules rules) throws ServiceException {
/* 1482 */     ZFilterRule newRule = ZFilterRule.parseFilterRule(args);
/* 1483 */     List<ZFilterRule> list = rules.getRules();
/* 1484 */     if (firstOpt()) {
/* 1485 */       list.add(0, newRule);
/* 1486 */     } else if (afterOpt() != null) {
/* 1487 */       boolean found = false;
/* 1488 */       String name = afterOpt();
/* 1489 */       for (int i = 0; i < list.size(); i++) {
/* 1490 */         found = ((ZFilterRule)list.get(i)).getName().equalsIgnoreCase(name);
/* 1491 */         if (found) {
/* 1492 */           if (i + 1 >= list.size()) {
/* 1493 */             list.add(newRule); break;
/*      */           }
/* 1495 */           list.add(i + 1, newRule);
/* 1496 */           break;
/*      */         }
/*      */       }
/* 1499 */       if (!found) {
/* 1500 */         throw ZClientException.CLIENT_ERROR("can't find rule: " + name, null);
/*      */       }
/* 1502 */     } else if (beforeOpt() != null) {
/* 1503 */       String name = beforeOpt();
/* 1504 */       boolean found = false;
/* 1505 */       for (int i = 0; i < list.size(); i++) {
/* 1506 */         found = ((ZFilterRule)list.get(i)).getName().equalsIgnoreCase(name);
/* 1507 */         if (found) {
/* 1508 */           list.add(i, newRule);
/* 1509 */           break;
/*      */         }
/*      */       }
/* 1512 */       if (!found) {
/* 1513 */         throw ZClientException.CLIENT_ERROR("can't find rule: " + name, null);
/*      */       }
/*      */     }
/*      */     else {
/* 1517 */       list.add(newRule);
/*      */     }
/*      */   }
/*      */   
/*      */   private void doModifyIncomingFilterRule(String[] args) throws ServiceException {
/* 1522 */     ZFilterRules rules = this.mMbox.getIncomingFilterRules(true);
/* 1523 */     doModifyFilterRule(args, rules);
/* 1524 */     this.mMbox.saveIncomingFilterRules(rules);
/*      */   }
/*      */   
/*      */   private void doModifyOutgoingFilterRule(String[] args) throws ServiceException {
/* 1528 */     ZFilterRules rules = this.mMbox.getOutgoingFilterRules(true);
/* 1529 */     doModifyFilterRule(args, rules);
/* 1530 */     this.mMbox.saveOutgoingFilterRules(rules);
/*      */   }
/*      */   
/*      */   private static void doModifyFilterRule(String[] args, ZFilterRules rules) throws ServiceException {
/* 1534 */     ZFilterRule modifiedRule = ZFilterRule.parseFilterRule(args);
/* 1535 */     List<ZFilterRule> list = rules.getRules();
/* 1536 */     for (int i = 0; i < list.size(); i++) {
/* 1537 */       if (((ZFilterRule)list.get(i)).getName().equalsIgnoreCase(modifiedRule.getName())) {
/* 1538 */         list.set(i, modifiedRule);
/* 1539 */         return;
/*      */       }
/*      */     }
/* 1542 */     throw ZClientException.CLIENT_ERROR("can't find rule: " + args[0], null);
/*      */   }
/*      */   
/*      */   private void doDeleteIncomingFilterRule(String[] args) throws ServiceException {
/* 1546 */     ZFilterRules rules = this.mMbox.getIncomingFilterRules(true);
/* 1547 */     doDeleteFilterRule(args, rules);
/* 1548 */     this.mMbox.saveIncomingFilterRules(rules);
/*      */   }
/*      */   
/*      */   private void doDeleteOutgoingFilterRule(String[] args) throws ServiceException {
/* 1552 */     ZFilterRules rules = this.mMbox.getOutgoingFilterRules(true);
/* 1553 */     doDeleteFilterRule(args, rules);
/* 1554 */     this.mMbox.saveOutgoingFilterRules(rules);
/*      */   }
/*      */   
/*      */   private static void doDeleteFilterRule(String[] args, ZFilterRules rules) throws ServiceException {
/* 1558 */     String name = args[0];
/* 1559 */     List<ZFilterRule> list = rules.getRules();
/* 1560 */     for (int i = 0; i < list.size(); i++) {
/* 1561 */       if (((ZFilterRule)list.get(i)).getName().equalsIgnoreCase(name)) {
/* 1562 */         list.remove(i);
/* 1563 */         return;
/*      */       }
/*      */     }
/* 1566 */     throw ZClientException.CLIENT_ERROR("can't find rule: " + args, null);
/*      */   }
/*      */   
/*      */   private void doGetIncomingFilterRules() throws ServiceException {
/* 1570 */     ZFilterRules rules = this.mMbox.getIncomingFilterRules(true);
/* 1571 */     printFilterRules(rules);
/*      */   }
/*      */   
/*      */   private void doGetOutgoingFilterRules() throws ServiceException {
/* 1575 */     ZFilterRules rules = this.mMbox.getOutgoingFilterRules(true);
/* 1576 */     printFilterRules(rules);
/*      */   }
/*      */   
/*      */   private static void printFilterRules(ZFilterRules rules) {
/* 1580 */     for (ZFilterRule r : rules.getRules()) {
/* 1581 */       stdout.println(r.generateFilterRule());
/*      */     }
/*      */   }
/*      */   
/*      */   private String getGranteeDisplay(ZGrant.GranteeType type) {
/* 1586 */     switch (type) {
/* 1587 */     case usr:  return "account";
/* 1588 */     case grp:  return "group";
/* 1589 */     case cos:  return "cos";
/* 1590 */     case pub:  return "public";
/* 1591 */     case all:  return "all";
/* 1592 */     case dom:  return "domain";
/* 1593 */     case guest:  return "guest";
/* 1594 */     case key:  return "key"; }
/* 1595 */     return "unknown";
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */   private ZFolder getFolderWithFullGrantInfo(String pathOrId)
/*      */     throws ServiceException
/*      */   {
/* 1606 */     ZFolder f = lookupFolder(pathOrId);
/* 1607 */     return this.mMbox.getFolderRequestById(f.getId());
/*      */   }
/*      */   
/*      */   private void doGetFolderGrant(String[] args) throws ServiceException {
/* 1611 */     ZFolder f = getFolderWithFullGrantInfo(args[0]);
/*      */     String format;
/* 1613 */     if (verboseOpt()) {
/* 1614 */       StringBuilder sb = new StringBuilder();
/* 1615 */       for (ZGrant g : f.getGrants()) {
/* 1616 */         if (sb.length() > 0) sb.append(",\n");
/* 1617 */         sb.append(g.dump());
/*      */       }
/* 1619 */       stdout.format("[%n%s%n]%n", new Object[] { sb.toString() });
/*      */     } else {
/* 1621 */       format = "%11.11s  %8.8s  %s%n";
/* 1622 */       stdout.format(format, new Object[] { "Permissions", "Type", "Display" });
/* 1623 */       stdout.format(format, new Object[] { "-----------", "--------", "-------" });
/*      */       
/* 1625 */       for (ZGrant g : f.getGrants()) {
/* 1626 */         ZGrant.GranteeType gt = g.getGranteeType();
/* 1627 */         String dn = g.getGranteeName() != null ? g.getGranteeName() : (gt == ZGrant.GranteeType.guest) || (gt == ZGrant.GranteeType.key) ? g.getGranteeId() : (gt == ZGrant.GranteeType.all) || (gt == ZGrant.GranteeType.pub) ? "" : g.getGranteeId();
/*      */         
/*      */ 
/*      */ 
/* 1631 */         stdout.format(format, new Object[] { g.getPermissions(), getGranteeDisplay(g.getGranteeType()), dn });
/*      */       }
/*      */     }
/*      */   }
/*      */   
/*      */   private ZGrant.GranteeType getGranteeType(String name) throws ServiceException {
/* 1637 */     if (name.equalsIgnoreCase("account")) return ZGrant.GranteeType.usr;
/* 1638 */     if (name.equalsIgnoreCase("group")) return ZGrant.GranteeType.grp;
/* 1639 */     if (name.equalsIgnoreCase("cos")) return ZGrant.GranteeType.cos;
/* 1640 */     if (name.equalsIgnoreCase("public")) return ZGrant.GranteeType.pub;
/* 1641 */     if (name.equalsIgnoreCase("all")) return ZGrant.GranteeType.all;
/* 1642 */     if (name.equalsIgnoreCase("domain")) return ZGrant.GranteeType.dom;
/* 1643 */     if (name.equalsIgnoreCase("guest")) return ZGrant.GranteeType.guest;
/* 1644 */     if (name.equalsIgnoreCase("key")) return ZGrant.GranteeType.key;
/* 1645 */     throw ZClientException.CLIENT_ERROR("unknown grantee type: " + name, null);
/*      */   }
/*      */   
/*      */   private void doModifyFolderGrant(String[] args) throws ServiceException {
/* 1649 */     String folderId = lookupFolderId(args[0], false);
/*      */     
/* 1651 */     ZGrant.GranteeType type = getGranteeType(args[1]);
/* 1652 */     String grantee = null;
/* 1653 */     String perms = null;
/* 1654 */     String password = null;
/* 1655 */     switch (type) {
/*      */     case usr: 
/*      */     case grp: 
/*      */     case cos: 
/*      */     case dom: 
/* 1660 */       if (args.length != 4) {
/* 1661 */         throw ZClientException.CLIENT_ERROR("not enough args", null);
/*      */       }
/* 1663 */       grantee = args[2];
/* 1664 */       perms = args[3];
/* 1665 */       break;
/*      */     case pub: 
/* 1667 */       grantee = "99999999-9999-9999-9999-999999999999";
/* 1668 */       perms = args[2];
/* 1669 */       break;
/*      */     case all: 
/* 1671 */       grantee = "00000000-0000-0000-0000-000000000000";
/* 1672 */       perms = args[2];
/* 1673 */       break;
/*      */     case guest: 
/* 1675 */       if ((args.length != 4) && (args.length != 5)) throw ZClientException.CLIENT_ERROR("not enough args", null);
/* 1676 */       grantee = args[2];
/* 1677 */       if (args.length == 5) {
/* 1678 */         password = args[3];
/* 1679 */         perms = args[4];
/*      */       } else {
/* 1681 */         password = null;
/* 1682 */         perms = args[3];
/*      */       }
/* 1684 */       break;
/*      */     case key: 
/* 1686 */       if ((args.length != 4) && (args.length != 5)) throw ZClientException.CLIENT_ERROR("not enough args", null);
/* 1687 */       grantee = args[2];
/* 1688 */       if (args.length == 5) {
/* 1689 */         password = args[3];
/* 1690 */         perms = args[4];
/*      */       } else {
/* 1692 */         perms = args[3];
/*      */       }
/*      */       break;
/*      */     }
/*      */     
/* 1697 */     boolean revoke = (perms != null) && ((perms.equalsIgnoreCase("none")) || (perms.length() == 0));
/*      */     
/* 1699 */     if (revoke)
/*      */     {
/* 1701 */       ZFolder f = getFolderWithFullGrantInfo(folderId);
/* 1702 */       String zid = null;
/* 1703 */       for (ZGrant g : f.getGrants()) {
/* 1704 */         if ((grantee.equalsIgnoreCase(g.getGranteeName())) || (grantee.equalsIgnoreCase(g.getGranteeId())))
/*      */         {
/* 1706 */           zid = g.getGranteeId();
/* 1707 */           break;
/*      */         }
/*      */       }
/*      */       
/* 1711 */       if ((zid != null) || (type == ZGrant.GranteeType.all) || (type == ZGrant.GranteeType.pub)) {
/* 1712 */         if (zid != null)
/* 1713 */           grantee = zid;
/* 1714 */         this.mMbox.modifyFolderRevokeGrant(folderId, grantee);
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */       }
/*      */       else
/*      */       {
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/* 1734 */         this.mMbox.modifyFolderGrant(folderId, type, grantee, "", password);
/*      */       }
/*      */     }
/*      */     else
/*      */     {
/* 1739 */       this.mMbox.modifyFolderGrant(folderId, type, grantee, perms, password);
/*      */     }
/*      */   }
/*      */   
/*      */   private void doListRights() throws ServiceException {
/* 1744 */     for (Right r : RightManager.getInstance().getAllUserRights().values()) {
/* 1745 */       stdout.println("  " + r.getName() + ": " + r.getDesc());
/* 1746 */       stdout.println();
/*      */     }
/*      */   }
/*      */   
/*      */   private void doGetRights(String[] args) throws ServiceException {
/*      */     String format;
/* 1752 */     if (verboseOpt()) {
/* 1753 */       StringBuilder sb = new StringBuilder();
/* 1754 */       for (ZAce g : this.mMbox.getRights(args)) {
/* 1755 */         if (sb.length() > 0) sb.append(",\n");
/* 1756 */         sb.append(g.dump());
/*      */       }
/* 1758 */       stdout.format("[%n%s%n]%n", new Object[] { sb.toString() });
/*      */     } else {
/* 1760 */       format = "%16.16s  %8.8s  %s%n";
/* 1761 */       stdout.format(format, new Object[] { "Right", "Type", "Display" });
/* 1762 */       stdout.format(format, new Object[] { "----------------", "--------", "-------" });
/*      */       
/* 1764 */       List<ZAce> result = this.mMbox.getRights(args);
/* 1765 */       Comparator<ZAce> comparator = new Comparator()
/*      */       {
/*      */         public int compare(ZAce a, ZAce b)
/*      */         {
/* 1769 */           String aKey = a.getRight() + a.getGranteeTypeSortOrder() + (a.getGranteeName() == null ? "" : a.getGranteeName());
/* 1770 */           String bKey = b.getRight() + b.getGranteeTypeSortOrder() + (b.getGranteeName() == null ? "" : b.getGranteeName());
/* 1771 */           int order = aKey.compareTo(bKey);
/* 1772 */           if (order == 0)
/* 1773 */             order = a.getDeny() ? -1 : 1;
/* 1774 */           return order;
/*      */         }
/* 1776 */       };
/* 1777 */       Collections.sort(result, comparator);
/*      */       
/* 1779 */       for (ZAce ace : result) {
/* 1780 */         stdout.format(format, new Object[] { ace.getRightDisplay(), ace.getGranteeTypeDisplay(), ace.getGranteeName() });
/*      */       }
/*      */     }
/* 1783 */     stdout.println();
/*      */   }
/*      */   
/*      */   private ZAce getAceFromArgs(String[] args) throws ServiceException {
/* 1787 */     ZAce.GranteeType type = ZAce.getGranteeTypeFromDisplay(args[0]);
/* 1788 */     String granteeName = null;
/* 1789 */     String granteeId = null;
/* 1790 */     String right = null;
/* 1791 */     boolean deny = false;
/* 1792 */     String secret = null;
/*      */     
/* 1794 */     switch (type) {
/*      */     case usr: 
/*      */     case grp: 
/*      */     case dom: 
/* 1798 */       if (args.length != 3) throw ZClientException.CLIENT_ERROR("wrong number of args", null);
/* 1799 */       granteeName = args[1];
/* 1800 */       right = args[2];
/* 1801 */       break;
/*      */     case all: 
/* 1803 */       if (args.length != 2) throw ZClientException.CLIENT_ERROR("wrong number of args", null);
/* 1804 */       granteeId = "00000000-0000-0000-0000-000000000000";
/* 1805 */       right = args[1];
/* 1806 */       break;
/*      */     case pub: 
/* 1808 */       if (args.length != 2) throw ZClientException.CLIENT_ERROR("wrong number of args", null);
/* 1809 */       granteeId = "99999999-9999-9999-9999-999999999999";
/* 1810 */       right = args[1];
/* 1811 */       break;
/*      */     case gst: 
/* 1813 */       if (args.length != 4) throw ZClientException.CLIENT_ERROR("wrong number of args", null);
/* 1814 */       granteeName = args[1];
/* 1815 */       secret = args[2];
/* 1816 */       right = args[3];
/* 1817 */       break;
/*      */     case key: 
/* 1819 */       if ((args.length != 3) && (args.length != 4)) throw ZClientException.CLIENT_ERROR("wrong number of args", null);
/* 1820 */       granteeName = args[1];
/* 1821 */       if (args.length == 3) {
/* 1822 */         right = args[2];
/*      */       } else {
/* 1824 */         secret = args[2];
/* 1825 */         right = args[3];
/*      */       }
/*      */       break;
/*      */     }
/*      */     
/* 1830 */     if (right.charAt(0) == '-') {
/* 1831 */       deny = true;
/* 1832 */       right = right.substring(1);
/*      */     }
/*      */     
/* 1835 */     return new ZAce(type, granteeId, granteeName, right, deny, secret);
/*      */   }
/*      */   
/*      */   private void doGrantRight(String[] args) throws ServiceException {
/* 1839 */     ZAce ace = getAceFromArgs(args);
/* 1840 */     List<ZAce> granted = this.mMbox.grantRight(ace);
/* 1841 */     if (granted.size() == 0) {
/* 1842 */       stdout.println("  granted no right");
/*      */     } else {
/* 1844 */       stdout.println("  granted: ");
/* 1845 */       for (ZAce g : granted)
/* 1846 */         stdout.println("    " + g.getGranteeTypeDisplay() + " " + g.getGranteeName() + " " + g.getRightDisplay());
/*      */     }
/*      */   }
/*      */   
/*      */   private void doRevokeRight(String[] args) throws ServiceException {
/* 1851 */     ZAce ace = getAceFromArgs(args);
/*      */     
/* 1853 */     ZAce.GranteeType granteeType = ace.getGranteeType();
/* 1854 */     if ((granteeType == ZAce.GranteeType.usr) || (granteeType == ZAce.GranteeType.grp) || (granteeType == ZAce.GranteeType.dom))
/*      */     {
/* 1856 */       String zid = null;
/* 1857 */       String granteeName = ace.getGranteeName();
/* 1858 */       String[] rights = { ace.getRight() };
/* 1859 */       for (ZAce g : this.mMbox.getRights(rights)) {
/* 1860 */         if ((granteeName.equalsIgnoreCase(g.getGranteeName())) || (granteeName.equalsIgnoreCase(g.getGranteeId())))
/*      */         {
/* 1862 */           zid = g.getGranteeId();
/* 1863 */           break;
/*      */         }
/*      */       }
/* 1866 */       if (zid == null)
/* 1867 */         throw ZClientException.CLIENT_ERROR("no such grant", null);
/* 1868 */       ace.setGranteeId(zid);
/*      */     }
/*      */     
/* 1871 */     List<ZAce> revoked = this.mMbox.revokeRight(ace);
/* 1872 */     if (revoked.size() == 0) {
/* 1873 */       stdout.println("  revoked no right");
/*      */     } else {
/* 1875 */       stdout.println("  revoked: ");
/* 1876 */       for (ZAce r : revoked)
/* 1877 */         stdout.println("    " + r.getGranteeTypeDisplay() + " " + r.getGranteeName() + " " + r.getRightDisplay());
/*      */     }
/*      */   }
/*      */   
/*      */   private void doCheckRight(String[] args) throws ServiceException {
/* 1882 */     String user = args[0];
/* 1883 */     List<String> rights = new ArrayList();
/* 1884 */     rights.add(args[1]);
/*      */     
/* 1886 */     boolean allow = this.mMbox.checkRights(user, rights);
/* 1887 */     stdout.println(allow ? "allowed" : "not allowed");
/*      */   }
/*      */   
/*      */   private void doAdminAuth(String[] args) throws ServiceException {
/* 1891 */     adminAuth(args[0], args[1], urlOpt(true));
/*      */   }
/*      */   
/*      */   private void doAuth(String[] args) throws ServiceException {
/* 1895 */     auth(args[0], args[1], param(args, 2, args[0]), urlOpt(true));
/*      */   }
/*      */   
/*      */   private void doSelectMailbox(String[] args) throws ServiceException {
/* 1899 */     String targetAccount = args[0];
/*      */     String authAccount;
/* 1901 */     String authAccount; if (this.mCommandLine.hasOption(O_AS_ADMIN.getLongOpt())) {
/* 1902 */       authAccount = null;
/*      */     } else {
/* 1904 */       authAccount = this.mCommandLine.getOptionValue(O_AUTH.getLongOpt());
/* 1905 */       if (StringUtil.isNullOrEmpty(authAccount)) {
/* 1906 */         authAccount = targetAccount;
/*      */       }
/*      */     }
/* 1909 */     selectMailbox(authAccount, targetAccount, this.mProv);
/*      */   }
/*      */   
/*      */ 
/*      */   static
/*      */   {
/*      */     try
/*      */     {
/* 1917 */       stdout = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8"), true);
/* 1918 */       stderr = new PrintWriter(new OutputStreamWriter(System.err, "UTF-8"), true);
/*      */     } catch (UnsupportedEncodingException e) {
/* 1920 */       e.printStackTrace();
/* 1921 */       System.exit(1);
/*      */     }
/* 1923 */     Properties props = new Properties();
/* 1924 */     props.setProperty("mail.mime.address.strict", "false");
/* 1925 */     mSession = Session.getInstance(props);
/*      */     
/*      */ 
/* 1928 */     System.setProperty("mail.mime.base64.ignoreerrors", "true");
/*      */   }
/*      */   
/*      */   private void addMessage(String folderId, String flags, String tags, long date, File file, boolean validate)
/*      */     throws ServiceException, IOException
/*      */   {
/* 1934 */     InputStream in = new BufferedInputStream(new FileInputStream(file));
/* 1935 */     long sizeHint = -1L;
/* 1936 */     if (ByteUtil.isGzipped(in)) {
/* 1937 */       in = new GZIPInputStream(in);
/*      */     } else {
/* 1939 */       sizeHint = file.length();
/*      */     }
/*      */     
/* 1942 */     byte[] data = ByteUtil.getContent(in, (int)sizeHint);
/* 1943 */     if ((validate) && (!EmailUtil.isRfc822Message(new ByteArrayInputStream(data)))) {
/* 1944 */       throw ZClientException.CLIENT_ERROR(file.getPath() + " does not contain a valid RFC 822 message", null);
/*      */     }
/*      */     try
/*      */     {
/* 1948 */       if (date == -1L) {
/* 1949 */         MimeMessage mm = new ZMimeMessage(mSession, new SharedByteArrayInputStream(data));
/* 1950 */         Date d = mm.getSentDate();
/* 1951 */         if (d != null) date = d.getTime(); else
/* 1952 */           date = 0L;
/*      */       }
/*      */     } catch (MessagingException e) {
/* 1955 */       date = 0L;
/*      */     }
/* 1957 */     String id = this.mMbox.addMessage(folderId, flags, tags, date, data, false);
/* 1958 */     stdout.format("%s (%s)%n", new Object[] { id, file.getPath() });
/*      */   }
/*      */   
/*      */   private void doAddMessage(String[] args) throws ServiceException, IOException {
/* 1962 */     String folderId = lookupFolderId(args[0], false);
/* 1963 */     String tags = tagsOpt();
/* 1964 */     String flags = flagsOpt();
/* 1965 */     long date = dateOpt(-1L);
/* 1966 */     boolean validate = validateOpt();
/*      */     
/* 1968 */     for (int i = 1; i < args.length; i++) {
/* 1969 */       File file = new File(args[i]);
/* 1970 */       if (file.isDirectory())
/*      */       {
/* 1972 */         for (File child : file.listFiles()) {
/* 1973 */           if (child.isFile())
/* 1974 */             addMessage(folderId, flags, tags, date, child, validate);
/*      */         }
/*      */       } else {
/* 1977 */         addMessage(folderId, flags, tags, date, file, validate);
/*      */       }
/*      */     }
/*      */   }
/*      */   
/*      */   private String emailAddrs(List<ZEmailAddress> addrs) {
/* 1983 */     StringBuilder sb = new StringBuilder();
/* 1984 */     for (ZEmailAddress e : addrs) {
/* 1985 */       if (sb.length() > 0) sb.append(", ");
/* 1986 */       sb.append(e.getDisplay());
/*      */     }
/* 1988 */     return sb.toString();
/*      */   }
/*      */   
/*      */   private void doCreateFolder(String[] args) throws ServiceException {
/* 1992 */     ZFolder cf = this.mMbox.createFolder(lookupFolderId(args[0], true), ZMailbox.getBasePath(args[0]), folderViewOpt(), folderColorOpt(), flagsOpt(), urlOpt(false));
/*      */     
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/* 1999 */     stdout.println(cf.getId());
/*      */   }
/*      */   
/*      */   private void doCreateSignature(String[] args) throws ServiceException {
/* 2003 */     ZSignature sig = new ZSignature(args[0], args[1]);
/* 2004 */     stdout.println(this.mMbox.createSignature(sig));
/*      */   }
/*      */   
/*      */   private void doModifySignature(String[] args) throws ServiceException {
/* 2008 */     ZSignature sig = lookupSignature(args[0]);
/* 2009 */     ZSignature modSig = new ZSignature(sig.getId(), sig.getName(), args[1]);
/* 2010 */     this.mMbox.modifySignature(modSig);
/*      */   }
/*      */   
/*      */   private void doRenameSignature(String[] args) throws ServiceException {
/* 2014 */     ZSignature sig = lookupSignature(args[0]);
/* 2015 */     ZSignature modSig = new ZSignature(sig.getId(), args[1], sig.getValue());
/* 2016 */     this.mMbox.modifySignature(modSig);
/*      */   }
/*      */   
/*      */   private ZSignature lookupSignature(String idOrName) throws ServiceException {
/* 2020 */     for (ZSignature sig : this.mMbox.getSignatures()) {
/* 2021 */       if ((sig.getName().equalsIgnoreCase(idOrName)) || (sig.getId().equalsIgnoreCase(idOrName)))
/* 2022 */         return sig;
/*      */     }
/* 2024 */     throw ZClientException.CLIENT_ERROR("unknown signature: " + idOrName, null);
/*      */   }
/*      */   
/*      */   private String lookupSignatureId(String idOrName) throws ServiceException {
/* 2028 */     if (StringUtil.isUUID(idOrName)) {
/* 2029 */       return idOrName;
/*      */     }
/* 2031 */     for (ZSignature sig : this.mMbox.getSignatures()) {
/* 2032 */       if (sig.getName().equalsIgnoreCase(idOrName)) {
/* 2033 */         return sig.getId();
/*      */       }
/*      */     }
/* 2036 */     throw ZClientException.CLIENT_ERROR("unknown signature: " + idOrName, null);
/*      */   }
/*      */   
/*      */   private void doCreateSearchFolder(String[] args) throws ServiceException
/*      */   {
/* 2041 */     ZSearchFolder csf = this.mMbox.createSearchFolder(lookupFolderId(args[0], true), ZMailbox.getBasePath(args[0]), args[1], typesOpt(), searchSortByOpt(), folderColorOpt());
/*      */     
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/* 2048 */     stdout.println(csf.getId());
/*      */   }
/*      */   
/*      */   private void doCreateMountpoint(String[] args) throws ServiceException {
/* 2052 */     String cmPath = args[0];
/* 2053 */     String cmOwner = args[1];
/* 2054 */     String cmItem = args[2];
/* 2055 */     boolean reminderEnabled = paramb(args, 3, false);
/*      */     
/* 2057 */     ZMailbox.OwnerBy ownerBy = ZMailbox.OwnerBy.BY_NAME;
/* 2058 */     if (StringUtil.isUUID(cmOwner)) {
/* 2059 */       ownerBy = ZMailbox.OwnerBy.BY_ID;
/*      */     }
/*      */     
/* 2062 */     ZMailbox.SharedItemBy sharedItemBy = ZMailbox.SharedItemBy.BY_PATH;
/* 2063 */     String sharedItem = cmItem;
/*      */     
/* 2065 */     int colonAt = cmItem.indexOf(':');
/* 2066 */     if ((colonAt != -1) && (colonAt != 0) && (colonAt != cmItem.length() - 1)) {
/* 2067 */       String itemOwnerId = cmItem.substring(0, colonAt);
/* 2068 */       String itemId = cmItem.substring(colonAt + 1);
/* 2069 */       if (StringUtil.isUUID(itemOwnerId)) {
/* 2070 */         sharedItemBy = ZMailbox.SharedItemBy.BY_ID;
/* 2071 */         sharedItem = itemId;
/*      */       }
/*      */     }
/*      */     
/* 2075 */     ZMountpoint cm = this.mMbox.createMountpoint(lookupFolderId(cmPath, true), ZMailbox.getBasePath(cmPath), folderViewOpt(), folderColorOpt(), flagsOpt(), ownerBy, cmOwner, sharedItemBy, sharedItem, reminderEnabled);
/*      */     
/* 2077 */     stdout.println(cm.getId());
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */ 
/*      */   private void doSearch(String[] args)
/*      */     throws ServiceException
/*      */   {
/* 2086 */     if (currrentOpt()) {
/* 2087 */       doSearchRedisplay();
/* 2088 */       return; }
/* 2089 */     if (previousOpt()) {
/* 2090 */       doSearchPrevious();
/* 2091 */       return; }
/* 2092 */     if (nextOpt()) {
/* 2093 */       doSearchNext();
/* 2094 */       return; }
/* 2095 */     if (args.length == 0) {
/* 2096 */       usage();
/* 2097 */       return;
/*      */     }
/*      */     
/* 2100 */     this.mSearchParams = new ZSearchParams(args[0]);
/*      */     
/*      */ 
/*      */ 
/* 2104 */     this.mSearchParams.setLimit(getOptLimit());
/*      */     
/* 2106 */     SearchSortBy sortBy = searchSortByOpt();
/* 2107 */     this.mSearchParams.setSortBy(sortBy != null ? sortBy : SearchSortBy.dateDesc);
/*      */     
/* 2109 */     String types = typesOpt();
/* 2110 */     this.mSearchParams.setTypes(types != null ? types : "conversation");
/*      */     
/* 2112 */     this.mSearchParams.setInDumpster(this.mCommandLine.hasOption(O_DUMPSTER.getLongOpt()));
/* 2113 */     this.mIndexToId.clear();
/* 2114 */     this.mSearchPage = 0;
/* 2115 */     ZSearchPagerResult pager = this.mMbox.search(this.mSearchParams, this.mSearchPage, false, false);
/*      */     
/* 2117 */     dumpSearch(pager.getResult(), verboseOpt());
/*      */   }
/*      */   
/*      */   private int getOptLimit() throws ServiceException {
/*      */     int limit;
/*      */     try {
/* 2123 */       limit = Integer.parseInt(this.mCommandLine.getOptionValue(O_LIMIT.getOpt(), "25"));
/*      */     } catch (NumberFormatException e) {
/* 2125 */       throw ZClientException.CLIENT_ERROR("limit must be a number", e);
/*      */     }
/* 2127 */     if ((limit <= 0) || (limit > 1000)) {
/* 2128 */       throw ZClientException.CLIENT_ERROR("limit must be 1-1000", null);
/*      */     }
/* 2130 */     return limit;
/*      */   }
/*      */   
/*      */   private void doSearchRedisplay() throws ServiceException {
/* 2134 */     if (this.mSearchParams == null) return;
/* 2135 */     ZSearchPagerResult pager = this.mMbox.search(this.mSearchParams, this.mSearchPage, true, false);
/* 2136 */     this.mSearchPage = pager.getActualPage();
/* 2137 */     if (pager.getResult().getHits().size() == 0) return;
/* 2138 */     dumpSearch(pager.getResult(), verboseOpt());
/*      */   }
/*      */   
/*      */   private void doSearchNext() throws ServiceException {
/* 2142 */     if (this.mSearchParams == null) return;
/* 2143 */     ZSearchPagerResult pager = this.mMbox.search(this.mSearchParams, ++this.mSearchPage, true, false);
/* 2144 */     this.mSearchPage = pager.getActualPage();
/* 2145 */     if (pager.getResult().getHits().size() == 0) return;
/* 2146 */     dumpSearch(pager.getResult(), verboseOpt());
/*      */   }
/*      */   
/*      */   private void doSearchPrevious() throws ServiceException {
/* 2150 */     if ((this.mSearchParams == null) || (this.mSearchPage == 0))
/* 2151 */       return;
/* 2152 */     ZSearchPagerResult pager = this.mMbox.search(this.mSearchParams, --this.mSearchPage, true, false);
/* 2153 */     this.mSearchPage = pager.getActualPage();
/* 2154 */     if (pager.getResult().getHits().size() == 0) return;
/* 2155 */     dumpSearch(pager.getResult(), verboseOpt());
/*      */   }
/*      */   
/*      */ 
/*      */   private void doSearchConv(String[] args)
/*      */     throws ServiceException
/*      */   {
/* 2162 */     if (currrentOpt()) {
/* 2163 */       doSearchConvRedisplay();
/* 2164 */       return; }
/* 2165 */     if (previousOpt()) {
/* 2166 */       doSearchConvPrevious();
/* 2167 */       return; }
/* 2168 */     if (nextOpt()) {
/* 2169 */       doSearchConvNext();
/* 2170 */       return; }
/* 2171 */     if (args.length != 2) {
/* 2172 */       usage();
/* 2173 */       return;
/*      */     }
/*      */     
/* 2176 */     this.mConvSearchConvId = id(args[0]);
/* 2177 */     this.mConvSearchParams = new ZSearchParams(args[1]);
/*      */     
/*      */ 
/*      */ 
/* 2181 */     this.mConvSearchParams.setLimit(getOptLimit());
/*      */     
/* 2183 */     SearchSortBy sortBy = searchSortByOpt();
/* 2184 */     this.mConvSearchParams.setSortBy(sortBy != null ? sortBy : SearchSortBy.dateDesc);
/*      */     
/* 2186 */     String types = typesOpt();
/* 2187 */     this.mConvSearchParams.setTypes(types != null ? types : "conversation");
/*      */     
/* 2189 */     this.mIndexToId.clear();
/*      */     
/* 2191 */     dumpConvSearch(this.mMbox.searchConversation(this.mConvSearchConvId, this.mConvSearchParams), verboseOpt());
/*      */   }
/*      */   
/*      */   private void doSearchConvRedisplay() {
/* 2195 */     ZSearchResult sr = this.mConvSearchResult;
/* 2196 */     if (sr == null) return;
/* 2197 */     dumpConvSearch(this.mConvSearchResult, verboseOpt());
/*      */   }
/*      */   
/*      */   private void doSearchConvNext() throws ServiceException {
/* 2201 */     ZSearchParams sp = this.mConvSearchParams;
/* 2202 */     ZSearchResult sr = this.mConvSearchResult;
/* 2203 */     if ((sp == null) || (sr == null) || (!sr.hasMore())) {
/* 2204 */       return;
/*      */     }
/* 2206 */     List<ZSearchHit> hits = sr.getHits();
/* 2207 */     if (hits.size() == 0) return;
/* 2208 */     sp.setOffset(sp.getOffset() + hits.size());
/* 2209 */     dumpConvSearch(this.mMbox.searchConversation(this.mConvSearchConvId, sp), verboseOpt());
/*      */   }
/*      */   
/*      */   private void doSearchConvPrevious() throws ServiceException {
/* 2213 */     ZSearchParams sp = this.mConvSearchParams;
/* 2214 */     ZSearchResult sr = this.mConvSearchResult;
/* 2215 */     if ((sp == null) || (sr == null) || (sp.getOffset() == 0))
/* 2216 */       return;
/* 2217 */     sp.setOffset(sp.getOffset() - sr.getHits().size());
/* 2218 */     dumpConvSearch(this.mMbox.searchConversation(this.mConvSearchConvId, sp), verboseOpt());
/*      */   }
/*      */   
/*      */   private int colWidth(int num) {
/* 2222 */     int i = 1;
/* 2223 */     while (num >= 10) {
/* 2224 */       i++;
/* 2225 */       num /= 10;
/*      */     }
/* 2227 */     return i;
/*      */   }
/*      */   
/*      */   private void dumpSearch(ZSearchResult sr, boolean verbose) {
/* 2231 */     if (verbose) {
/* 2232 */       stdout.println(sr.dump());
/* 2233 */       return;
/*      */     }
/*      */     
/* 2236 */     int offset = this.mSearchPage * this.mSearchParams.getLimit();
/* 2237 */     int first = offset + 1;
/* 2238 */     int last = offset + sr.getHits().size();
/*      */     
/* 2240 */     stdout.printf("num: %d, more: %s%n%n", new Object[] { Integer.valueOf(sr.getHits().size()), Boolean.valueOf(sr.hasMore()) });
/* 2241 */     int width = colWidth(last);
/*      */     
/* 2243 */     if (sr.getHits().size() == 0) {
/* 2244 */       return;
/*      */     }
/*      */     
/* 2247 */     int FROM_LEN = 20;
/* 2248 */     int id_len = 4;
/* 2249 */     for (ZSearchHit hit : sr.getHits()) {
/* 2250 */       id_len = Math.max(id_len, hit.getId().length());
/*      */     }
/*      */     
/* 2253 */     Calendar cal = Calendar.getInstance();
/* 2254 */     String headerFormat = String.format("%%%d.%ds  %%%d.%ds  %%4s   %%-20.20s  %%-50.50s  %%s%%n", new Object[] { Integer.valueOf(width), Integer.valueOf(width), Integer.valueOf(id_len), Integer.valueOf(id_len) });
/*      */     
/* 2256 */     String itemFormat = String.format("%%%d.%ds. %%%d.%ds  %%4s   %%-20.20s  %%-50.50s  %%tD %%<tR%%n", new Object[] { Integer.valueOf(width), Integer.valueOf(width), Integer.valueOf(id_len), Integer.valueOf(id_len) });
/*      */     
/* 2258 */     stdout.format(headerFormat, new Object[] { "", "Id", "Type", "From", "Subject", "Date" });
/* 2259 */     stdout.format(headerFormat, new Object[] { "", "----------------------------------------------------------------------------------------------------", "----", "--------------------", "--------------------------------------------------", "--------------" });
/*      */     
/*      */ 
/* 2262 */     int i = first;
/* 2263 */     for (ZSearchHit hit : sr.getHits()) {
/* 2264 */       if ((hit instanceof ZConversationHit)) {
/* 2265 */         ZConversationHit ch = (ZConversationHit)hit;
/* 2266 */         cal.setTimeInMillis(ch.getDate());
/* 2267 */         String sub = ch.getSubject();
/* 2268 */         String from = emailAddrs(ch.getRecipients());
/* 2269 */         if (ch.getMessageCount() > 1) {
/* 2270 */           String numMsg = " (" + ch.getMessageCount() + ")";
/* 2271 */           int space = 20 - numMsg.length();
/* 2272 */           from = (from.length() < space ? from : from.substring(0, space)) + numMsg;
/*      */         }
/*      */         
/*      */ 
/* 2276 */         this.mIndexToId.put(Integer.valueOf(i), ch.getId());
/* 2277 */         stdout.format(itemFormat, new Object[] { Integer.valueOf(i++), ch.getId(), "conv", from, sub, cal });
/* 2278 */       } else if ((hit instanceof ZContactHit)) {
/* 2279 */         ZContactHit ch = (ZContactHit)hit;
/* 2280 */         cal.setTimeInMillis(ch.getDate());
/* 2281 */         String from = getFirstEmail(ch);
/* 2282 */         String sub = ch.getFileAsStr();
/* 2283 */         this.mIndexToId.put(Integer.valueOf(i), ch.getId());
/* 2284 */         stdout.format(itemFormat, new Object[] { Integer.valueOf(i++), ch.getId(), "cont", from, sub, cal });
/* 2285 */       } else if ((hit instanceof ZMessageHit)) {
/* 2286 */         ZMessageHit mh = (ZMessageHit)hit;
/* 2287 */         cal.setTimeInMillis(mh.getDate());
/* 2288 */         String sub = mh.getSubject();
/* 2289 */         String from = mh.getSender() == null ? "<none>" : mh.getSender().getDisplay();
/* 2290 */         this.mIndexToId.put(Integer.valueOf(i), mh.getId());
/* 2291 */         stdout.format(itemFormat, new Object[] { Integer.valueOf(i++), mh.getId(), "mess", from, sub, cal });
/* 2292 */       } else if ((hit instanceof ZAppointmentHit)) {
/* 2293 */         ZAppointmentHit ah = (ZAppointmentHit)hit;
/* 2294 */         if (ah.getInstanceExpanded()) {
/* 2295 */           cal.setTimeInMillis(ah.getStartTime());
/*      */         } else {
/* 2297 */           cal.setTimeInMillis(ah.getHitDate());
/*      */         }
/* 2299 */         String sub = ah.getName();
/* 2300 */         String from = "<na>";
/* 2301 */         this.mIndexToId.put(Integer.valueOf(i), ah.getId());
/* 2302 */         stdout.format(itemFormat, new Object[] { Integer.valueOf(i++), ah.getId(), ah.getIsTask() ? "task" : "appo", from, sub, cal });
/* 2303 */       } else if ((hit instanceof ZDocumentHit)) {
/* 2304 */         ZDocumentHit dh = (ZDocumentHit)hit;
/* 2305 */         ZDocument doc = dh.getDocument();
/* 2306 */         cal.setTimeInMillis(doc.getModifiedDate());
/* 2307 */         String name = doc.getName();
/* 2308 */         String editor = doc.getEditor();
/* 2309 */         this.mIndexToId.put(Integer.valueOf(i), dh.getId());
/* 2310 */         stdout.format(itemFormat, new Object[] { Integer.valueOf(i++), dh.getId(), doc.isWiki() ? "wiki" : "doc", editor, name, cal });
/*      */       }
/*      */     }
/* 2313 */     stdout.println();
/*      */   }
/*      */   
/*      */   private String getFirstEmail(ZContactHit ch) {
/* 2317 */     if (ch.getEmail() != null) return ch.getEmail();
/* 2318 */     if (ch.getEmail2() != null) return ch.getEmail2();
/* 2319 */     if (ch.getEmail3() != null) return ch.getEmail3();
/* 2320 */     return "<none>";
/*      */   }
/*      */   
/*      */   private void dumpConvSearch(ZSearchResult sr, boolean verbose) {
/* 2324 */     this.mConvSearchResult = sr;
/* 2325 */     if (verbose) {
/* 2326 */       stdout.println(sr.dump());
/* 2327 */       return;
/*      */     }
/*      */     
/* 2330 */     int offset = sr.getOffset();
/* 2331 */     int first = offset + 1;
/* 2332 */     int last = offset + sr.getHits().size();
/*      */     
/* 2334 */     stdout.printf("num: %d, more: %s%n%n", new Object[] { Integer.valueOf(sr.getHits().size()), Boolean.valueOf(sr.hasMore()) });
/* 2335 */     int width = colWidth(last);
/*      */     
/* 2337 */     if (sr.getHits().size() == 0) {
/* 2338 */       return;
/*      */     }
/*      */     
/* 2341 */     int id_len = 4;
/* 2342 */     for (ZSearchHit hit : sr.getHits()) {
/* 2343 */       id_len = Math.max(id_len, hit.getId().length());
/*      */     }
/*      */     
/* 2346 */     Calendar c = Calendar.getInstance();
/* 2347 */     String headerFormat = String.format("%%%d.%ds  %%%d.%ds  %%-20.20s  %%-50.50s  %%s%%n", new Object[] { Integer.valueOf(width), Integer.valueOf(width), Integer.valueOf(id_len), Integer.valueOf(id_len) });
/*      */     
/*      */ 
/* 2350 */     String itemFormat = String.format("%%%d.%ds. %%%d.%ds  %%-20.20s  %%-50.50s  %%tD %%<tR%%n", new Object[] { Integer.valueOf(width), Integer.valueOf(width), Integer.valueOf(id_len), Integer.valueOf(id_len) });
/*      */     
/*      */ 
/* 2353 */     stdout.format(headerFormat, new Object[] { "", "Id", "From", "Subject", "Date" });
/* 2354 */     stdout.format(headerFormat, new Object[] { "", "----------------------------------------------------------------------------------------------------", "--------------------", "--------------------------------------------------", "--------------" });
/* 2355 */     int i = first;
/* 2356 */     for (ZSearchHit hit : sr.getHits()) {
/* 2357 */       if ((hit instanceof ZMessageHit)) {
/* 2358 */         ZMessageHit mh = (ZMessageHit)hit;
/* 2359 */         c.setTimeInMillis(mh.getDate());
/* 2360 */         String sub = mh.getSubject();
/* 2361 */         String from = mh.getSender().getDisplay();
/* 2362 */         this.mIndexToId.put(Integer.valueOf(i), mh.getId());
/* 2363 */         stdout.format(itemFormat, new Object[] { Integer.valueOf(i++), mh.getId(), from, sub, c });
/*      */       }
/*      */     }
/* 2366 */     stdout.println();
/*      */   }
/*      */   
/*      */   private void doGetAllTags() throws ServiceException {
/* 2370 */     if (verboseOpt()) {
/* 2371 */       StringBuilder sb = new StringBuilder();
/* 2372 */       for (String tagName : this.mMbox.getAllTagNames()) {
/* 2373 */         ZTag tag = this.mMbox.getTagByName(tagName);
/* 2374 */         if (sb.length() > 0) sb.append(",\n");
/* 2375 */         sb.append(tag.dump());
/*      */       }
/* 2377 */       stdout.format("[%n%s%n]%n", new Object[] { sb.toString() });
/*      */     } else {
/* 2379 */       if (this.mMbox.getAllTagNames().size() == 0) return;
/* 2380 */       String hdrFormat = "%10.10s  %10.10s  %10.10s  %s%n";
/* 2381 */       stdout.format(hdrFormat, new Object[] { "Id", "Unread", "Color", "Name" });
/* 2382 */       stdout.format(hdrFormat, new Object[] { "----------", "----------", "----------", "----------" });
/* 2383 */       for (String tagName : this.mMbox.getAllTagNames()) {
/* 2384 */         ZTag tag = this.mMbox.getTagByName(tagName);
/* 2385 */         stdout.format("%10.10s  %10d  %10.10s  %s%n", new Object[] { tag.getId(), Integer.valueOf(tag.getUnreadCount()), tag.getColor().name(), tag.getName() });
/*      */       }
/*      */     }
/*      */   }
/*      */   
/*      */   private void doDumpFolder(ZFolder folder, boolean recurse) {
/*      */     String path;
/*      */     String path;
/* 2393 */     if ((folder instanceof ZSearchFolder)) {
/* 2394 */       path = String.format("%s (%s)", new Object[] { folder.getPath(), ((ZSearchFolder)folder).getQuery() }); } else { String path;
/* 2395 */       if ((folder instanceof ZMountpoint)) {
/* 2396 */         ZMountpoint mp = (ZMountpoint)folder;
/* 2397 */         path = String.format("%s (%s:%s)", new Object[] { folder.getPath(), mp.getOwnerDisplayName(), mp.getRemoteId() }); } else { String path;
/* 2398 */         if (folder.getRemoteURL() != null) {
/* 2399 */           path = String.format("%s (%s)", new Object[] { folder.getPath(), folder.getRemoteURL() });
/*      */         } else
/* 2401 */           path = folder.getPath();
/*      */       }
/*      */     }
/* 2404 */     stdout.format("%10.10s  %4.4s  %10d  %10d  %s%n", new Object[] { folder.getId(), folder.getDefaultView().name(), Integer.valueOf(folder.getUnreadCount()), Integer.valueOf(folder.getMessageCount()), path });
/*      */     
/* 2406 */     if (recurse) {
/* 2407 */       for (ZFolder child : folder.getSubFolders()) {
/* 2408 */         doDumpFolder(child, recurse);
/*      */       }
/*      */     }
/*      */   }
/*      */   
/*      */   private void doGetAllFolders() throws ServiceException {
/* 2414 */     if (verboseOpt()) {
/* 2415 */       stdout.println(this.mMbox.getUserRoot().dump());
/*      */     } else {
/* 2417 */       String hdrFormat = "%10.10s  %4.4s  %10.10s  %10.10s  %s%n";
/* 2418 */       stdout.format(hdrFormat, new Object[] { "Id", "View", "Unread", "Msg Count", "Path" });
/* 2419 */       stdout.format(hdrFormat, new Object[] { "----------", "----", "----------", "----------", "----------" });
/* 2420 */       doDumpFolder(this.mMbox.getUserRoot(), true);
/*      */     }
/*      */   }
/*      */   
/*      */   private void doGetFolder(String[] args) throws ServiceException {
/* 2425 */     ZFolder f = lookupFolder(args[0]);
/* 2426 */     stdout.println(f.dump());
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */   private void doGetFolderRequest(String[] args)
/*      */     throws ServiceException
/*      */   {
/* 2437 */     ZFolder f = this.mMbox.getFolderRequestById(args[0]);
/* 2438 */     stdout.println(f);
/*      */   }
/*      */   
/*      */   private void dumpIdentities(List<ZIdentity> identities) {
/* 2442 */     if (verboseOpt()) {
/* 2443 */       stdout.println("[");
/* 2444 */       boolean first = true;
/* 2445 */       for (ZIdentity identity : identities) {
/* 2446 */         if (first) first = false; else stdout.println(",");
/* 2447 */         stdout.println(identity.dump());
/*      */       }
/* 2449 */       stdout.println("]");
/*      */     } else {
/* 2451 */       if (identities.size() == 0) return;
/* 2452 */       for (ZIdentity identity : identities) {
/* 2453 */         stdout.println(identity.getName());
/*      */       }
/*      */     }
/*      */   }
/*      */   
/*      */   private void doGetIdentities() throws ServiceException {
/* 2459 */     dumpIdentities(this.mMbox.getIdentities());
/*      */   }
/*      */   
/*      */   private void dumpSignatures(List<ZSignature> signatures) {
/* 2463 */     if (verboseOpt()) {
/* 2464 */       stdout.println("[");
/* 2465 */       boolean first = true;
/* 2466 */       for (ZSignature sig : signatures) {
/* 2467 */         if (first) first = false; else stdout.println(",");
/* 2468 */         stdout.println(sig.dump());
/*      */       }
/* 2470 */       stdout.println("]");
/*      */     } else {
/* 2472 */       if (signatures.size() == 0) return;
/* 2473 */       for (ZSignature sig : signatures) {
/* 2474 */         stdout.println(sig.getName());
/*      */       }
/*      */     }
/*      */   }
/*      */   
/*      */   private void doGetSignatures() throws ServiceException {
/* 2480 */     dumpSignatures(this.mMbox.getSignatures());
/*      */   }
/*      */   
/*      */   private void dumpContacts(List<ZContact> contacts) throws ServiceException
/*      */   {
/* 2485 */     if (verboseOpt()) {
/* 2486 */       stdout.println("[");
/* 2487 */       boolean first = true;
/* 2488 */       for (ZContact cn : contacts) {
/* 2489 */         if (first) first = false; else stdout.println(",");
/* 2490 */         stdout.println(cn.dump());
/*      */       }
/* 2492 */       stdout.println("]");
/*      */     } else {
/* 2494 */       if (contacts.size() == 0) return;
/* 2495 */       for (ZContact cn : contacts) {
/* 2496 */         dumpContact(cn);
/*      */       }
/*      */     }
/*      */   }
/*      */   
/*      */   private void dumpAutoCompleteMatches(List<ZAutoCompleteMatch> matches) {
/* 2502 */     if (matches.isEmpty()) {
/* 2503 */       stdout.println("no matches");
/* 2504 */       return;
/*      */     }
/* 2506 */     int idLen = 2;
/* 2507 */     int fidLen = 3;
/* 2508 */     int displayLen = 7;
/* 2509 */     for (ZAutoCompleteMatch match : matches) {
/* 2510 */       String id = match.getId();
/* 2511 */       if ((id != null) && (id.length() > idLen))
/* 2512 */         idLen = id.length();
/* 2513 */       String fid = match.getFolderId();
/* 2514 */       if ((fid != null) && (fid.length() > fidLen))
/* 2515 */         fidLen = fid.length();
/* 2516 */       String display = match.getDisplayName();
/* 2517 */       if ((display != null) && (display.length() > displayLen))
/* 2518 */         displayLen = display.length();
/*      */     }
/* 2520 */     String format = "%7s %7s";
/* 2521 */     if (verboseOpt()) {
/* 2522 */       format = format + String.format(" %%%d.%ds", new Object[] { Integer.valueOf(idLen), Integer.valueOf(idLen) });
/* 2523 */       format = format + String.format(" %%%d.%ds", new Object[] { Integer.valueOf(fidLen), Integer.valueOf(fidLen) });
/* 2524 */       format = format + String.format(" %%%d.%ds", new Object[] { Integer.valueOf(displayLen), Integer.valueOf(displayLen) });
/*      */     }
/* 2526 */     format = format + " %s %n";
/* 2527 */     if (verboseOpt()) {
/* 2528 */       stdout.format(format, new Object[] { "Ranking", "type", "id", "fid", "display", "email" });
/* 2529 */       stdout.println("-------------------------------------------------------------------");
/*      */     } else {
/* 2531 */       stdout.format(format, new Object[] { "Ranking", "type", "email" });
/* 2532 */       stdout.println("-------------------------------------------------------------------");
/*      */     }
/* 2534 */     for (ZAutoCompleteMatch match : matches) {
/* 2535 */       if (verboseOpt()) {
/* 2536 */         String folderId = match.getFolderId();
/* 2537 */         String id = match.getId();
/* 2538 */         String display = match.getDisplayName();
/* 2539 */         if (folderId == null) folderId = "";
/* 2540 */         if (id == null) id = "";
/* 2541 */         if (display == null) display = "";
/* 2542 */         stdout.format(format, new Object[] { match.getRanking(), match.getType(), id, folderId, display, match.getEmail() });
/*      */       } else {
/* 2544 */         stdout.format(format, new Object[] { match.getRanking(), match.getType(), match.getEmail() });
/*      */       }
/*      */     }
/*      */   }
/*      */   
/*      */   private void doGetAllContacts(String[] args) throws ServiceException {
/* 2550 */     dumpContacts(this.mMbox.getAllContacts(lookupFolderId(folderOpt()), null, true, getList(args, 0)));
/*      */   }
/*      */   
/*      */   private void doGetContacts(String[] args) throws ServiceException {
/* 2554 */     dumpContacts(this.mMbox.getContacts(id(args[0]), null, true, getList(args, 1)));
/*      */   }
/*      */   
/*      */   private void doAutoComplete(String[] args) throws ServiceException {
/* 2558 */     dumpAutoCompleteMatches(this.mMbox.autoComplete(args[0], 20));
/*      */   }
/*      */   
/*      */   private void doAutoCompleteGal(String[] args) throws ServiceException {
/* 2562 */     ZMailbox.ZSearchGalResult result = this.mMbox.autoCompleteGal(args[0], ZMailbox.GalEntryType.account, 20);
/* 2563 */     dumpContacts(result.getContacts());
/*      */   }
/*      */   
/*      */   private void dumpConversation(ZConversation conv) throws ServiceException {
/* 2567 */     int first = 1;
/* 2568 */     int last = first + conv.getMessageCount();
/* 2569 */     int width = colWidth(last);
/*      */     
/* 2571 */     this.mIndexToId.clear();
/*      */     
/* 2573 */     stdout.format("%nSubject: %s%n", new Object[] { conv.getSubject() });
/* 2574 */     stdout.format("Id: %s%n", new Object[] { conv.getId() });
/*      */     
/* 2576 */     if (conv.hasTags()) stdout.format("Tags: %s%n", new Object[] { lookupTagNames(conv.getTagIds()) });
/* 2577 */     if (conv.hasFlags()) stdout.format("Flags: %s%n", new Object[] { ZConversation.Flag.toNameList(conv.getFlags()) });
/* 2578 */     stdout.format("Num-Messages: %d%n%n", new Object[] { Integer.valueOf(conv.getMessageCount()) });
/*      */     
/* 2580 */     if (conv.getMessageCount() == 0) { return;
/*      */     }
/* 2582 */     int id_len = 4;
/* 2583 */     for (ZConversation.ZMessageSummary ms : conv.getMessageSummaries()) {
/* 2584 */       id_len = Math.max(id_len, ms.getId().length());
/*      */     }
/*      */     
/* 2587 */     String headerFormat = String.format("%%%d.%ds  %%%d.%ds  %%-15.15s  %%-50.50s  %%s%%n", new Object[] { Integer.valueOf(width), Integer.valueOf(width), Integer.valueOf(id_len), Integer.valueOf(id_len) });
/* 2588 */     String itemFormat = String.format("%%%d.%ds. %%%d.%ds  %%-15.15s  %%-50.50s  %%tD %%<tR%%n", new Object[] { Integer.valueOf(width), Integer.valueOf(width), Integer.valueOf(id_len), Integer.valueOf(id_len) });
/* 2589 */     stdout.format(headerFormat, new Object[] { "", "Id", "Sender", "Fragment", "Date" });
/* 2590 */     stdout.format(headerFormat, new Object[] { "", "----------------------------------------------------------------------------------------------------", "---------------", "--------------------------------------------------", "--------------" });
/* 2591 */     int i = first;
/* 2592 */     for (ZConversation.ZMessageSummary ms : conv.getMessageSummaries()) {
/* 2593 */       stdout.format(itemFormat, new Object[] { Integer.valueOf(i), ms.getId(), ms.getSender().getDisplay(), ms.getFragment(), Long.valueOf(ms.getDate()) });
/*      */       
/* 2595 */       this.mIndexToId.put(Integer.valueOf(i++), ms.getId());
/*      */     }
/* 2597 */     stdout.println();
/*      */   }
/*      */   
/*      */   private void doGetConversation(String[] args) throws ServiceException {
/* 2601 */     ZConversation conv = this.mMbox.getConversation(id(args[0]), ZMailbox.Fetch.none);
/* 2602 */     if (verboseOpt()) {
/* 2603 */       stdout.println(conv.dump());
/*      */     } else {
/* 2605 */       dumpConversation(conv);
/*      */     }
/*      */   }
/*      */   
/*      */   private static int addEmail(StringBuilder sb, String email, int line) {
/* 2610 */     if (sb.length() > 0) { sb.append(',');line++; }
/* 2611 */     if (line > 76) { sb.append("\n");line = 1; }
/* 2612 */     if (sb.length() > 0) { sb.append(' ');line++; }
/* 2613 */     if ((line > 20) && (line + email.length() > 76)) {
/* 2614 */       sb.append("\n ");
/* 2615 */       line = 1;
/*      */     }
/* 2617 */     sb.append(email);
/* 2618 */     line += email.length();
/* 2619 */     return line;
/*      */   }
/*      */   
/*      */   public static String formatEmail(ZEmailAddress e) {
/* 2623 */     String p = e.getPersonal();
/* 2624 */     String a = e.getAddress();
/* 2625 */     if (a == null) a = "";
/* 2626 */     if (p == null) {
/* 2627 */       return String.format("<%s>", new Object[] { a });
/*      */     }
/* 2629 */     return String.format("%s <%s>", new Object[] { p, a });
/*      */   }
/*      */   
/*      */   public static String formatEmail(List<ZEmailAddress> list, String type, int used) {
/* 2633 */     if ((list == null) || (list.size() == 0)) { return "";
/*      */     }
/* 2635 */     StringBuilder sb = new StringBuilder();
/*      */     
/* 2637 */     for (ZEmailAddress e : list) {
/* 2638 */       if (e.getType().equalsIgnoreCase(type)) {
/* 2639 */         String fe = formatEmail(e);
/* 2640 */         used = addEmail(sb, fe, used);
/*      */       }
/*      */     }
/* 2643 */     return sb.toString();
/*      */   }
/*      */   
/*      */   private void doHeader(List<ZEmailAddress> list, String hdrName, String addrType) {
/* 2647 */     String val = formatEmail(list, addrType, hdrName.length() + 2);
/* 2648 */     if ((val == null) || (val.length() == 0)) return;
/* 2649 */     stdout.format("%s: %s%n", new Object[] { hdrName, val });
/*      */   }
/*      */   
/*      */   private void dumpMessage(ZMessage msg) throws ServiceException {
/* 2653 */     stdout.format("Id: %s%n", new Object[] { msg.getId() });
/* 2654 */     stdout.format("Conversation-Id: %s%n", new Object[] { msg.getConversationId() });
/* 2655 */     ZFolder f = this.mMbox.getFolderById(msg.getFolderId());
/* 2656 */     stdout.format("Folder: %s%n", new Object[] { f == null ? msg.getFolderId() : f.getPath() });
/* 2657 */     stdout.format("Subject: %s%n", new Object[] { msg.getSubject() });
/* 2658 */     doHeader(msg.getEmailAddresses(), "From", "f");
/* 2659 */     doHeader(msg.getEmailAddresses(), "To", "t");
/* 2660 */     doHeader(msg.getEmailAddresses(), "Cc", "c");
/* 2661 */     stdout.format("Date: %s\n", new Object[] { DateUtil.toRFC822Date(new Date(msg.getReceivedDate())) });
/* 2662 */     if (msg.hasTags()) stdout.format("Tags: %s%n", new Object[] { lookupTagNames(msg.getTagIds()) });
/* 2663 */     if (msg.hasFlags()) stdout.format("Flags: %s%n", new Object[] { ZItem.Flag.toNameList(msg.getFlags()) });
/* 2664 */     stdout.format("Size: %s%n", new Object[] { formatSize(msg.getSize()) });
/* 2665 */     stdout.println();
/* 2666 */     if (dumpBody(msg.getMimeStructure()))
/* 2667 */       stdout.println();
/*      */   }
/*      */   
/*      */   private void doGetMessage(String[] args) throws ServiceException {
/* 2671 */     ZGetMessageParams params = new ZGetMessageParams();
/* 2672 */     params.setMarkRead(true);
/* 2673 */     params.setId(id(args[0]));
/* 2674 */     ZMessage msg = this.mMbox.getMessage(params);
/* 2675 */     if (verboseOpt()) {
/* 2676 */       stdout.println(msg.dump());
/*      */     } else {
/* 2678 */       dumpMessage(msg);
/*      */     }
/*      */   }
/*      */   
/*      */   private boolean dumpBody(ZMessage.ZMimePart mp) {
/* 2683 */     if (mp == null) { return false;
/*      */     }
/* 2685 */     if (mp.isBody()) {
/* 2686 */       stdout.println(mp.getContent());
/* 2687 */       return true;
/*      */     }
/* 2689 */     for (ZMessage.ZMimePart child : mp.getChildren()) {
/* 2690 */       if (dumpBody(child)) { return true;
/*      */       }
/*      */     }
/* 2693 */     return false;
/*      */   }
/*      */   
/*      */   private void doModifyContact(String[] args) throws ServiceException {
/* 2697 */     String id = this.mMbox.modifyContact(id(args[0]), this.mCommandLine.hasOption('r'), getContactMap(args, 1, !ignoreOpt())).getId();
/* 2698 */     stdout.println(id);
/*      */   }
/*      */   
/*      */   private void dumpContact(ZContact contact) throws ServiceException {
/* 2702 */     stdout.format("Id: %s%n", new Object[] { contact.getId() });
/* 2703 */     ZFolder f = this.mMbox.getFolderById(contact.getFolderId());
/* 2704 */     stdout.format("Folder: %s%n", new Object[] { f == null ? contact.getFolderId() : f.getPath() });
/* 2705 */     stdout.format("Date: %tD %<tR%n", new Object[] { Long.valueOf(contact.getMetaDataChangedDate()) });
/* 2706 */     if (contact.hasTags()) stdout.format("Tags: %s%n", new Object[] { lookupTagNames(contact.getTagIds()) });
/* 2707 */     if (contact.hasFlags()) stdout.format("Flags: %s%n", new Object[] { ZContact.Flag.toNameList(contact.getFlags()) });
/* 2708 */     stdout.format("Revision: %s%n", new Object[] { contact.getRevision() });
/* 2709 */     stdout.format("Attrs:%n", new Object[0]);
/* 2710 */     Map<String, String> attrs = contact.getAttrs();
/* 2711 */     for (Map.Entry<String, String> entry : attrs.entrySet()) {
/* 2712 */       stdout.format("  %s: %s%n", new Object[] { entry.getKey(), entry.getValue() });
/*      */     }
/* 2714 */     if (contact.isGroup()) {
/* 2715 */       stdout.format("GroupMembers: %s%n", new Object[] { contact.getMembers().keySet() });
/*      */     }
/* 2717 */     stdout.println();
/*      */   }
/*      */   
/*      */   private Map<String, String> getContactMap(String[] args, int offset, boolean validate) throws ServiceException {
/* 2721 */     Map<String, String> result = getMap(args, offset);
/* 2722 */     if (validate) {
/* 2723 */       for (String name : result.keySet()) {
/* 2724 */         ContactConstants.Attr.fromString(name);
/*      */       }
/*      */     }
/* 2727 */     return result;
/*      */   }
/*      */   
/*      */   private Map<String, Object> getMultiMap(String[] args, int offset) throws ServiceException {
/*      */     try {
/* 2732 */       return StringUtil.keyValueArrayToMultiMap(args, offset);
/*      */     } catch (IllegalArgumentException iae) {
/* 2734 */       throw ZClientException.CLIENT_ERROR("not enough arguments", null);
/*      */     }
/*      */   }
/*      */   
/*      */   private Map<String, String> getMap(String[] args, int offset) throws ServiceException {
/* 2739 */     Map<String, String> attrs = new HashMap();
/* 2740 */     for (int i = offset; i < args.length; i += 2) {
/* 2741 */       String n = args[i];
/* 2742 */       if (i + 1 >= args.length)
/* 2743 */         throw ZClientException.CLIENT_ERROR("not enough arguments", null);
/* 2744 */       String v = args[(i + 1)];
/* 2745 */       attrs.put(n, v);
/*      */     }
/* 2747 */     return attrs;
/*      */   }
/*      */   
/*      */   private List<String> getList(String[] args, int offset) {
/* 2751 */     List<String> attrs = new ArrayList();
/* 2752 */     for (int i = offset; i < args.length; i++) {
/* 2753 */       attrs.add(args[i]);
/*      */     }
/* 2755 */     return attrs;
/*      */   }
/*      */   
/*      */   public void interactive(BufferedReader in) throws IOException {
/*      */     for (;;) {
/* 2760 */       stdout.print(this.mPrompt);
/* 2761 */       stdout.flush();
/* 2762 */       String line = StringUtil.readLine(in);
/* 2763 */       if ((line == null) || (line.length() == -1))
/*      */         break;
/* 2765 */       if (this.mGlobalVerbose) {
/* 2766 */         stdout.println(line);
/*      */       }
/* 2768 */       String[] args = StringUtil.parseLine(line);
/* 2769 */       if (args.length != 0)
/*      */         try
/*      */         {
/* 2772 */           switch (execute(args)) {
/*      */           case EXIT: 
/* 2774 */             return;
/*      */           }
/*      */         }
/*      */         catch (ServiceException e) {
/* 2778 */           Throwable cause = e.getCause();
/* 2779 */           stderr.println("ERROR: " + e.getCode() + " (" + e.getMessage() + ")" + (cause == null ? "" : new StringBuilder().append(" (cause: ").append(cause.getClass().getName()).append(" ").append(cause.getMessage()).append(")").toString()));
/*      */           
/* 2781 */           if (this.mGlobalVerbose) e.printStackTrace(stderr);
/*      */         }
/*      */     }
/*      */   }
/*      */   
/*      */   public static void main(String[] args) throws IOException, ServiceException {
/* 2787 */     CliUtil.toolSetup();
/* 2788 */     SoapTransport.setDefaultUserAgent("zmmailbox", BuildInfo.VERSION);
/*      */     
/* 2790 */     ZMailboxUtil pu = new ZMailboxUtil();
/* 2791 */     CommandLineParser parser = new GnuParser();
/* 2792 */     Options options = new Options();
/* 2793 */     options.addOption("a", "admin", true, "admin account name to auth as");
/* 2794 */     options.addOption("z", "zadmin", false, "use zimbra admin name/password from localconfig for admin/password");
/* 2795 */     options.addOption("h", "help", false, "display usage");
/* 2796 */     options.addOption("f", "file", true, "use file as input stream");
/* 2797 */     options.addOption("u", "url", true, "http[s]://host[:port] of server to connect to");
/* 2798 */     options.addOption("r", "protocol", true, "protocol to use for request/response [soap11, soap12, json]");
/* 2799 */     options.addOption("m", "mailbox", true, "mailbox to open");
/* 2800 */     options.addOption(null, "auth", true, "account name to auth as; defaults to -m unless -A is used");
/* 2801 */     options.addOption("A", "admin-priv", false, "execute requests with admin privileges");
/* 2802 */     options.addOption("p", "password", true, "auth password");
/* 2803 */     options.addOption("P", "passfile", true, "filename with password in it");
/* 2804 */     options.addOption("t", "timeout", true, "timeout (in seconds)");
/* 2805 */     options.addOption("v", "verbose", false, "verbose mode");
/* 2806 */     options.addOption("d", "debug", false, "debug mode");
/* 2807 */     options.addOption(SoapCLI.OPT_AUTHTOKEN);
/* 2808 */     options.addOption(SoapCLI.OPT_AUTHTOKENFILE);
/*      */     
/* 2810 */     CommandLine cl = null;
/* 2811 */     boolean err = false;
/*      */     try
/*      */     {
/* 2814 */       cl = parser.parse(options, args, true);
/*      */     } catch (ParseException pe) {
/* 2816 */       stderr.println("error: " + pe.getMessage());
/* 2817 */       err = true;
/*      */     }
/*      */     
/* 2820 */     if ((err) || (cl.hasOption('h'))) {
/* 2821 */       pu.usage();
/*      */     }
/*      */     try
/*      */     {
/* 2825 */       boolean isAdmin = false;
/* 2826 */       pu.setVerbose(cl.hasOption('v'));
/* 2827 */       if (cl.hasOption('a')) {
/* 2828 */         pu.setAdminAccountName(cl.getOptionValue('a'));
/* 2829 */         pu.setUrl(DEFAULT_ADMIN_URL, true);
/* 2830 */         isAdmin = true;
/*      */       }
/* 2832 */       if (cl.hasOption('z')) {
/* 2833 */         pu.setAdminAccountName(LC.zimbra_ldap_user.value());
/* 2834 */         pu.setPassword(LC.zimbra_ldap_password.value());
/* 2835 */         pu.setUrl(DEFAULT_ADMIN_URL, true);
/* 2836 */         isAdmin = true;
/*      */       }
/*      */       
/* 2839 */       if ((cl.hasOption("y")) && (cl.hasOption("Y")))
/* 2840 */         pu.usage();
/* 2841 */       if (cl.hasOption("y")) {
/* 2842 */         pu.setAdminAuthToken(ZAuthToken.fromJSONString(cl.getOptionValue("y")));
/* 2843 */         pu.setUrl(DEFAULT_ADMIN_URL, true);
/* 2844 */         isAdmin = true;
/*      */       }
/* 2846 */       if (cl.hasOption("Y")) {
/* 2847 */         String authToken = StringUtil.readSingleLineFromFile(cl.getOptionValue("Y"));
/* 2848 */         pu.setAdminAuthToken(ZAuthToken.fromJSONString(authToken));
/* 2849 */         pu.setUrl(DEFAULT_ADMIN_URL, true);
/* 2850 */         isAdmin = true;
/*      */       }
/*      */       String targetAccount;
/*      */       String targetAccount;
/* 2854 */       if (cl.hasOption('m')) {
/* 2855 */         targetAccount = cl.getOptionValue('m');
/*      */       } else {
/* 2857 */         targetAccount = null;
/*      */       }
/* 2859 */       if (((cl.hasOption("A")) || (cl.hasOption("auth"))) && (!cl.hasOption('m')))
/* 2860 */         throw ZClientException.CLIENT_ERROR("-A/--auth requires -m", null);
/*      */       String authAccount;
/* 2862 */       String authAccount; if (cl.hasOption("A")) {
/* 2863 */         if (!isAdmin) {
/* 2864 */           throw ZClientException.CLIENT_ERROR("-A requires admin auth", null);
/*      */         }
/* 2866 */         if (cl.hasOption("auth")) {
/* 2867 */           throw ZClientException.CLIENT_ERROR("-A cannot be combined with --auth", null);
/*      */         }
/* 2869 */         authAccount = null; } else { String authAccount;
/* 2870 */         if (cl.hasOption("auth")) {
/* 2871 */           authAccount = cl.getOptionValue("auth");
/*      */         }
/*      */         else
/* 2874 */           authAccount = targetAccount;
/*      */       }
/* 2876 */       if (!StringUtil.isNullOrEmpty(authAccount)) pu.setAuthAccountName(authAccount);
/* 2877 */       if (!StringUtil.isNullOrEmpty(targetAccount)) { pu.setTargetAccountName(targetAccount);
/*      */       }
/* 2879 */       if (cl.hasOption('u')) pu.setUrl(cl.getOptionValue('u'), isAdmin);
/* 2880 */       if (cl.hasOption('p')) pu.setPassword(cl.getOptionValue('p'));
/* 2881 */       if (cl.hasOption('P')) {
/* 2882 */         pu.setPassword(StringUtil.readSingleLineFromFile(cl.getOptionValue('P')));
/*      */       }
/* 2884 */       if (cl.hasOption('d')) { pu.setDebug(true);
/*      */       }
/* 2886 */       if (cl.hasOption('t')) { pu.setTimeout(cl.getOptionValue('t'));
/*      */       }
/* 2888 */       args = cl.getArgs();
/*      */       
/* 2890 */       pu.setInteractive(args.length < 1);
/*      */       
/* 2892 */       pu.initMailbox();
/* 2893 */       if (args.length < 1) {
/* 2894 */         InputStream is = null;
/* 2895 */         if (cl.hasOption('f')) {
/* 2896 */           is = new FileInputStream(cl.getOptionValue('f'));
/*      */         } else {
/* 2898 */           if (LC.command_line_editing_enabled.booleanValue()) {
/*      */             try {
/* 2900 */               CliUtil.enableCommandLineEditing(LC.zimbra_home.value() + "/.zmmailbox_history");
/*      */             } catch (IOException e) {
/* 2902 */               System.err.println("Command line editing will be disabled: " + e);
/* 2903 */               if (pu.mGlobalVerbose) {
/* 2904 */                 e.printStackTrace(System.err);
/*      */               }
/*      */             }
/*      */           }
/* 2908 */           is = System.in;
/*      */         }
/* 2910 */         pu.interactive(new BufferedReader(new InputStreamReader(is, "UTF-8")));
/*      */       } else {
/* 2912 */         pu.execute(args);
/*      */       }
/*      */     } catch (ServiceException e) {
/* 2915 */       Throwable cause = e.getCause();
/* 2916 */       stderr.println("ERROR: " + e.getCode() + " (" + e.getMessage() + ")" + (cause == null ? "" : new StringBuilder().append(" (cause: ").append(cause.getClass().getName()).append(" ").append(cause.getMessage()).append(")").toString()));
/*      */       
/* 2918 */       if (pu.mGlobalVerbose) e.printStackTrace(stderr);
/* 2919 */       System.exit(2);
/*      */     }
/*      */   }
/*      */   
/*      */   private void doHelp(String[] args) {
/* 2924 */     Category cat = null;
/* 2925 */     if ((args != null) && (args.length >= 1)) {
/* 2926 */       String s = args[0].toUpperCase();
/*      */       Category[] arr$;
/* 2928 */       int len$; int i$; try { cat = Category.valueOf(s);
/*      */       } catch (IllegalArgumentException e) {
/* 2930 */         arr$ = Category.values();len$ = arr$.length;i$ = 0; } for (; i$ < len$; i$++) { Category c = arr$[i$];
/* 2931 */         if (c.name().startsWith(s)) {
/* 2932 */           cat = c;
/* 2933 */           break;
/*      */         }
/*      */       }
/*      */     }
/*      */     
/*      */ 
/* 2939 */     if ((args == null) || (args.length == 0) || (cat == null)) {
/* 2940 */       stdout.println(" zmmailbox is used for mailbox management. Try:");
/* 2941 */       stdout.println("");
/* 2942 */       for (Category c : Category.values()) {
/* 2943 */         stdout.printf("     zmmailbox help %-15s %s\n", new Object[] { c.name().toLowerCase(), c.getDescription() });
/*      */       }
/*      */     }
/*      */     
/*      */ 
/* 2948 */     if (cat != null) {
/* 2949 */       stdout.println("");
/* 2950 */       for (Command c : Command.values()) {
/* 2951 */         if ((c.hasHelp()) && (
/* 2952 */           (cat == Category.COMMANDS) || (cat == c.getCategory()))) {
/* 2953 */           stdout.print(c.getFullUsage());
/* 2954 */           stdout.println();
/*      */         }
/*      */       }
/* 2957 */       if (cat.getCategoryHelp() != null)
/* 2958 */         stdout.println(cat.getCategoryHelp());
/*      */     }
/* 2960 */     stdout.println();
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */   public void receiveSoapMessage(Element envelope)
/*      */   {
/* 2967 */     long end = System.currentTimeMillis();
/* 2968 */     stdout.printf("======== SOAP RECEIVE =========\n", new Object[0]);
/* 2969 */     stdout.println(envelope.prettyPrint());
/* 2970 */     stdout.printf("=============================== (%d msecs)\n", new Object[] { Long.valueOf(end - this.mSendStart) });
/*      */   }
/*      */   
/*      */ 
/*      */   public void sendSoapMessage(Element envelope)
/*      */   {
/* 2976 */     this.mSendStart = System.currentTimeMillis();
/* 2977 */     stdout.println("========== SOAP SEND ==========");
/* 2978 */     stdout.println(envelope.prettyPrint());
/* 2979 */     stdout.println("===============================");
/*      */   }
/*      */   
/*      */   public static String encodeURL(String unencoded)
/*      */   {
/* 2984 */     String queryString = null;
/* 2985 */     int queryStringStart = unencoded.indexOf('?');
/* 2986 */     if (queryStringStart != -1) {
/* 2987 */       queryString = unencoded.substring(queryStringStart);
/* 2988 */       unencoded = unencoded.substring(0, queryStringStart);
/*      */     }
/* 2990 */     StringBuilder encoded = new StringBuilder();
/* 2991 */     String[] parts = unencoded.split("/");
/* 2992 */     if (parts != null) {
/* 2993 */       for (int i = 0; i < parts.length; i++) {
/* 2994 */         parts[i] = HttpUtil.encodePath(parts[i]);
/*      */       }
/* 2996 */       encoded.append(StringUtil.join("/", parts));
/*      */     } else {
/* 2998 */       encoded.append(unencoded);
/*      */     }
/* 3000 */     if (queryString != null) {
/*      */       String encodedQuery;
/*      */       try {
/* 3003 */         URI uri = new URI(null, null, null, queryString.substring(1), null);
/* 3004 */         encodedQuery = uri.toString();
/*      */       } catch (URISyntaxException e) {
/* 3006 */         encodedQuery = queryString;
/*      */       }
/* 3008 */       encoded.append(encodedQuery);
/*      */     }
/* 3010 */     return encoded.toString();
/*      */   }
/*      */   
/*      */   private void doGetRestURL(String[] args) throws ServiceException {
/* 3014 */     OutputStream os = null;
/* 3015 */     String outputFile = outputFileOpt();
/* 3016 */     boolean hasOutputFile = outputFile != null;
/*      */     try
/*      */     {
/* 3019 */       os = hasOutputFile ? new FileOutputStream(outputFile) : System.out;
/* 3020 */       this.mMbox.getRESTResource(encodeURL(args[0]), os, hasOutputFile, startTimeOpt(), endTimeOpt(), this.mTimeout, urlOpt(false)); return;
/*      */     } catch (IOException e) {
/* 3022 */       throw ZClientException.IO_ERROR(e.getMessage(), e);
/*      */     } finally {
/* 3024 */       if ((hasOutputFile) && (os != null)) try { os.close();
/*      */         } catch (IOException e) {}
/*      */     }
/*      */   }
/*      */   
/*      */   private void doPostRestURL(String[] args) throws ServiceException {
/* 3030 */     try { File file = new File(args[1]);
/* 3031 */       this.mMbox.postRESTResource(encodeURL(args[0]), new FileInputStream(file), true, file.length(), contentTypeOpt(), ignoreAndContinueOnErrorOpt(), preserveAlarmsOpt(), this.mTimeout, urlOpt(false));
/*      */     }
/*      */     catch (FileNotFoundException e) {
/* 3034 */       throw ZClientException.CLIENT_ERROR("file not found: " + args[1], e);
/*      */     }
/*      */   }
/*      */   
/*      */   private void doEnableSharedReminder(String[] args)
/*      */     throws ServiceException
/*      */   {}
/*      */ }


/* Location:              /home/mint/zimbrastore.jar!/com/zimbra/cs/zclient/ZMailboxUtil.class
 * Java compiler version: 7 (51.0)
 * JD-Core Version:       0.7.1
 */